Home | History | Annotate | Download | only in dist
      1 /******************************************************************************
      2 ** This file is an amalgamation of many separate C source files from SQLite
      3 ** version 3.6.22.  By combining all the individual C code files into this
      4 ** single large file, the entire code can be compiled as a one translation
      5 ** unit.  This allows many compilers to do optimizations that would not be
      6 ** possible if the files were compiled separately.  Performance improvements
      7 ** of 5% are more are commonly seen when SQLite is compiled as a single
      8 ** translation unit.
      9 **
     10 ** This file is all you need to compile SQLite.  To use SQLite in other
     11 ** programs, you need this file and the "sqlite3.h" header file that defines
     12 ** the programming interface to the SQLite library.  (If you do not have
     13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
     14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
     15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
     16 ** if you want a wrapper to interface SQLite with your choice of programming
     17 ** language. The code for the "sqlite3" command-line shell is also in a
     18 ** separate file. This file contains only code for the core SQLite library.
     19 */
     20 #define SQLITE_CORE 1
     21 #define SQLITE_AMALGAMATION 1
     22 #ifndef SQLITE_PRIVATE
     23 # define SQLITE_PRIVATE static
     24 #endif
     25 #ifndef SQLITE_API
     26 # define SQLITE_API
     27 #endif
     28 /************** Begin file sqliteInt.h ***************************************/
     29 /*
     30 ** 2001 September 15
     31 **
     32 ** The author disclaims copyright to this source code.  In place of
     33 ** a legal notice, here is a blessing:
     34 **
     35 **    May you do good and not evil.
     36 **    May you find forgiveness for yourself and forgive others.
     37 **    May you share freely, never taking more than you give.
     38 **
     39 *************************************************************************
     40 ** Internal interface definitions for SQLite.
     41 **
     42 */
     43 #ifndef _SQLITEINT_H_
     44 #define _SQLITEINT_H_
     45 
     46 /*
     47 ** These #defines should enable >2GB file support on POSIX if the
     48 ** underlying operating system supports it.  If the OS lacks
     49 ** large file support, or if the OS is windows, these should be no-ops.
     50 **
     51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
     52 ** system #includes.  Hence, this block of code must be the very first
     53 ** code in all source files.
     54 **
     55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
     56 ** on the compiler command line.  This is necessary if you are compiling
     57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
     58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
     59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
     60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
     61 ** portability you should omit LFS.
     62 **
     63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
     64 */
     65 #ifndef SQLITE_DISABLE_LFS
     66 # define _LARGE_FILE       1
     67 # ifndef _FILE_OFFSET_BITS
     68 #   define _FILE_OFFSET_BITS 64
     69 # endif
     70 # define _LARGEFILE_SOURCE 1
     71 #endif
     72 
     73 /*
     74 ** Include the configuration header output by 'configure' if we're using the
     75 ** autoconf-based build
     76 */
     77 #ifdef _HAVE_SQLITE_CONFIG_H
     78 #include "config.h"
     79 #endif
     80 
     81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
     82 /************** Begin file sqliteLimit.h *************************************/
     83 /*
     84 ** 2007 May 7
     85 **
     86 ** The author disclaims copyright to this source code.  In place of
     87 ** a legal notice, here is a blessing:
     88 **
     89 **    May you do good and not evil.
     90 **    May you find forgiveness for yourself and forgive others.
     91 **    May you share freely, never taking more than you give.
     92 **
     93 *************************************************************************
     94 **
     95 ** This file defines various limits of what SQLite can process.
     96 */
     97 
     98 /*
     99 ** The maximum length of a TEXT or BLOB in bytes.   This also
    100 ** limits the size of a row in a table or index.
    101 **
    102 ** The hard limit is the ability of a 32-bit signed integer
    103 ** to count the size: 2^31-1 or 2147483647.
    104 */
    105 #ifndef SQLITE_MAX_LENGTH
    106 # define SQLITE_MAX_LENGTH 1000000000
    107 #endif
    108 
    109 /*
    110 ** This is the maximum number of
    111 **
    112 **    * Columns in a table
    113 **    * Columns in an index
    114 **    * Columns in a view
    115 **    * Terms in the SET clause of an UPDATE statement
    116 **    * Terms in the result set of a SELECT statement
    117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
    118 **    * Terms in the VALUES clause of an INSERT statement
    119 **
    120 ** The hard upper limit here is 32676.  Most database people will
    121 ** tell you that in a well-normalized database, you usually should
    122 ** not have more than a dozen or so columns in any table.  And if
    123 ** that is the case, there is no point in having more than a few
    124 ** dozen values in any of the other situations described above.
    125 */
    126 #ifndef SQLITE_MAX_COLUMN
    127 # define SQLITE_MAX_COLUMN 2000
    128 #endif
    129 
    130 /*
    131 ** The maximum length of a single SQL statement in bytes.
    132 **
    133 ** It used to be the case that setting this value to zero would
    134 ** turn the limit off.  That is no longer true.  It is not possible
    135 ** to turn this limit off.
    136 */
    137 #ifndef SQLITE_MAX_SQL_LENGTH
    138 # define SQLITE_MAX_SQL_LENGTH 1000000000
    139 #endif
    140 
    141 /*
    142 ** The maximum depth of an expression tree. This is limited to
    143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
    144 ** want to place more severe limits on the complexity of an
    145 ** expression.
    146 **
    147 ** A value of 0 used to mean that the limit was not enforced.
    148 ** But that is no longer true.  The limit is now strictly enforced
    149 ** at all times.
    150 */
    151 #ifndef SQLITE_MAX_EXPR_DEPTH
    152 # define SQLITE_MAX_EXPR_DEPTH 1000
    153 #endif
    154 
    155 /*
    156 ** The maximum number of terms in a compound SELECT statement.
    157 ** The code generator for compound SELECT statements does one
    158 ** level of recursion for each term.  A stack overflow can result
    159 ** if the number of terms is too large.  In practice, most SQL
    160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
    161 ** any limit on the number of terms in a compount SELECT.
    162 */
    163 #ifndef SQLITE_MAX_COMPOUND_SELECT
    164 # define SQLITE_MAX_COMPOUND_SELECT 500
    165 #endif
    166 
    167 /*
    168 ** The maximum number of opcodes in a VDBE program.
    169 ** Not currently enforced.
    170 */
    171 #ifndef SQLITE_MAX_VDBE_OP
    172 # define SQLITE_MAX_VDBE_OP 25000
    173 #endif
    174 
    175 /*
    176 ** The maximum number of arguments to an SQL function.
    177 */
    178 #ifndef SQLITE_MAX_FUNCTION_ARG
    179 # define SQLITE_MAX_FUNCTION_ARG 127
    180 #endif
    181 
    182 /*
    183 ** The maximum number of in-memory pages to use for the main database
    184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
    185 */
    186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
    187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
    188 #endif
    189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
    190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
    191 #endif
    192 
    193 /*
    194 ** The maximum number of attached databases.  This must be between 0
    195 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
    196 ** is used internally to track attached databases.
    197 */
    198 #ifndef SQLITE_MAX_ATTACHED
    199 # define SQLITE_MAX_ATTACHED 10
    200 #endif
    201 
    202 
    203 /*
    204 ** The maximum value of a ?nnn wildcard that the parser will accept.
    205 */
    206 #ifndef SQLITE_MAX_VARIABLE_NUMBER
    207 # define SQLITE_MAX_VARIABLE_NUMBER 999
    208 #endif
    209 
    210 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
    211 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
    212 ** and the fact that the page size must be a power of 2.
    213 **
    214 ** If this limit is changed, then the compiled library is technically
    215 ** incompatible with an SQLite library compiled with a different limit. If
    216 ** a process operating on a database with a page-size of 65536 bytes
    217 ** crashes, then an instance of SQLite compiled with the default page-size
    218 ** limit will not be able to rollback the aborted transaction. This could
    219 ** lead to database corruption.
    220 */
    221 #ifndef SQLITE_MAX_PAGE_SIZE
    222 # define SQLITE_MAX_PAGE_SIZE 32768
    223 #endif
    224 
    225 
    226 /*
    227 ** The default size of a database page.
    228 */
    229 #ifndef SQLITE_DEFAULT_PAGE_SIZE
    230 # define SQLITE_DEFAULT_PAGE_SIZE 1024
    231 #endif
    232 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    233 # undef SQLITE_DEFAULT_PAGE_SIZE
    234 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    235 #endif
    236 
    237 /*
    238 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
    239 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
    240 ** device characteristics (sector-size and atomic write() support),
    241 ** SQLite may choose a larger value. This constant is the maximum value
    242 ** SQLite will choose on its own.
    243 */
    244 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
    245 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
    246 #endif
    247 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    248 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
    249 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    250 #endif
    251 
    252 
    253 /*
    254 ** Maximum number of pages in one database file.
    255 **
    256 ** This is really just the default value for the max_page_count pragma.
    257 ** This value can be lowered (or raised) at run-time using that the
    258 ** max_page_count macro.
    259 */
    260 #ifndef SQLITE_MAX_PAGE_COUNT
    261 # define SQLITE_MAX_PAGE_COUNT 1073741823
    262 #endif
    263 
    264 /*
    265 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
    266 ** operator.
    267 */
    268 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
    269 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
    270 #endif
    271 
    272 /*
    273 ** Maximum depth of recursion for triggers.
    274 **
    275 ** A value of 1 means that a trigger program will not be able to itself
    276 ** fire any triggers. A value of 0 means that no trigger programs at all
    277 ** may be executed.
    278 */
    279 #ifndef SQLITE_MAX_TRIGGER_DEPTH
    280 # define SQLITE_MAX_TRIGGER_DEPTH 1000
    281 #endif
    282 
    283 /************** End of sqliteLimit.h *****************************************/
    284 /************** Continuing where we left off in sqliteInt.h ******************/
    285 
    286 /* Disable nuisance warnings on Borland compilers */
    287 #if defined(__BORLANDC__)
    288 #pragma warn -rch /* unreachable code */
    289 #pragma warn -ccc /* Condition is always true or false */
    290 #pragma warn -aus /* Assigned value is never used */
    291 #pragma warn -csu /* Comparing signed and unsigned */
    292 #pragma warn -spa /* Suspicious pointer arithmetic */
    293 #endif
    294 
    295 /* Needed for various definitions... */
    296 #ifndef _GNU_SOURCE
    297 # define _GNU_SOURCE
    298 #endif
    299 
    300 /*
    301 ** Include standard header files as necessary
    302 */
    303 #ifdef HAVE_STDINT_H
    304 #include <stdint.h>
    305 #endif
    306 #ifdef HAVE_INTTYPES_H
    307 #include <inttypes.h>
    308 #endif
    309 
    310 #define SQLITE_INDEX_SAMPLES 10
    311 
    312 /*
    313 ** This macro is used to "hide" some ugliness in casting an int
    314 ** value to a ptr value under the MSVC 64-bit compiler.   Casting
    315 ** non 64-bit values to ptr types results in a "hard" error with
    316 ** the MSVC 64-bit compiler which this attempts to avoid.
    317 **
    318 ** A simple compiler pragma or casting sequence could not be found
    319 ** to correct this in all situations, so this macro was introduced.
    320 **
    321 ** It could be argued that the intptr_t type could be used in this
    322 ** case, but that type is not available on all compilers, or
    323 ** requires the #include of specific headers which differs between
    324 ** platforms.
    325 **
    326 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
    327 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
    328 ** So we have to define the macros in different ways depending on the
    329 ** compiler.
    330 */
    331 #if defined(__GNUC__)
    332 # if defined(HAVE_STDINT_H)
    333 #   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
    334 #   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
    335 # else
    336 #   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
    337 #   define SQLITE_PTR_TO_INT(X)  ((int)(X))
    338 # endif
    339 #else
    340 # define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
    341 # define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
    342 #endif
    343 
    344 
    345 /*
    346 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
    347 ** Older versions of SQLite used an optional THREADSAFE macro.
    348 ** We support that for legacy
    349 */
    350 #if !defined(SQLITE_THREADSAFE)
    351 #if defined(THREADSAFE)
    352 # define SQLITE_THREADSAFE THREADSAFE
    353 #else
    354 # define SQLITE_THREADSAFE 1
    355 #endif
    356 #endif
    357 
    358 /*
    359 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
    360 ** It determines whether or not the features related to
    361 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
    362 ** be overridden at runtime using the sqlite3_config() API.
    363 */
    364 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
    365 # define SQLITE_DEFAULT_MEMSTATUS 1
    366 #endif
    367 
    368 /*
    369 ** Exactly one of the following macros must be defined in order to
    370 ** specify which memory allocation subsystem to use.
    371 **
    372 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
    373 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
    374 **     SQLITE_MEMORY_SIZE            // internal allocator #1
    375 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
    376 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
    377 **
    378 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
    379 ** the default.
    380 */
    381 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    382     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    383     defined(SQLITE_POW2_MEMORY_SIZE)>1
    384 # error "At most one of the following compile-time configuration options\
    385  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
    386  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
    387 #endif
    388 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    389     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    390     defined(SQLITE_POW2_MEMORY_SIZE)==0
    391 # define SQLITE_SYSTEM_MALLOC 1
    392 #endif
    393 
    394 /*
    395 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
    396 ** sizes of memory allocations below this value where possible.
    397 */
    398 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
    399 # define SQLITE_MALLOC_SOFT_LIMIT 1024
    400 #endif
    401 
    402 /*
    403 ** We need to define _XOPEN_SOURCE as follows in order to enable
    404 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
    405 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
    406 ** so it is omitted there.  See ticket #2673.
    407 **
    408 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
    409 ** implemented on some systems.  So we avoid defining it at all
    410 ** if it is already defined or if it is unneeded because we are
    411 ** not doing a threadsafe build.  Ticket #2681.
    412 **
    413 ** See also ticket #2741.
    414 */
    415 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
    416 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
    417 #endif
    418 
    419 /*
    420 ** The TCL headers are only needed when compiling the TCL bindings.
    421 */
    422 #if defined(SQLITE_TCL) || defined(TCLSH)
    423 # include <tcl.h>
    424 #endif
    425 
    426 /*
    427 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    428 ** Setting NDEBUG makes the code smaller and run faster.  So the following
    429 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
    430 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
    431 ** feature.
    432 */
    433 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
    434 # define NDEBUG 1
    435 #endif
    436 
    437 /*
    438 ** The testcase() macro is used to aid in coverage testing.  When
    439 ** doing coverage testing, the condition inside the argument to
    440 ** testcase() must be evaluated both true and false in order to
    441 ** get full branch coverage.  The testcase() macro is inserted
    442 ** to help ensure adequate test coverage in places where simple
    443 ** condition/decision coverage is inadequate.  For example, testcase()
    444 ** can be used to make sure boundary values are tested.  For
    445 ** bitmask tests, testcase() can be used to make sure each bit
    446 ** is significant and used at least once.  On switch statements
    447 ** where multiple cases go to the same block of code, testcase()
    448 ** can insure that all cases are evaluated.
    449 **
    450 */
    451 #ifdef SQLITE_COVERAGE_TEST
    452 SQLITE_PRIVATE   void sqlite3Coverage(int);
    453 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
    454 #else
    455 # define testcase(X)
    456 #endif
    457 
    458 /*
    459 ** The TESTONLY macro is used to enclose variable declarations or
    460 ** other bits of code that are needed to support the arguments
    461 ** within testcase() and assert() macros.
    462 */
    463 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
    464 # define TESTONLY(X)  X
    465 #else
    466 # define TESTONLY(X)
    467 #endif
    468 
    469 /*
    470 ** Sometimes we need a small amount of code such as a variable initialization
    471 ** to setup for a later assert() statement.  We do not want this code to
    472 ** appear when assert() is disabled.  The following macro is therefore
    473 ** used to contain that setup code.  The "VVA" acronym stands for
    474 ** "Verification, Validation, and Accreditation".  In other words, the
    475 ** code within VVA_ONLY() will only run during verification processes.
    476 */
    477 #ifndef NDEBUG
    478 # define VVA_ONLY(X)  X
    479 #else
    480 # define VVA_ONLY(X)
    481 #endif
    482 
    483 /*
    484 ** The ALWAYS and NEVER macros surround boolean expressions which
    485 ** are intended to always be true or false, respectively.  Such
    486 ** expressions could be omitted from the code completely.  But they
    487 ** are included in a few cases in order to enhance the resilience
    488 ** of SQLite to unexpected behavior - to make the code "self-healing"
    489 ** or "ductile" rather than being "brittle" and crashing at the first
    490 ** hint of unplanned behavior.
    491 **
    492 ** In other words, ALWAYS and NEVER are added for defensive code.
    493 **
    494 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
    495 ** be true and false so that the unreachable code then specify will
    496 ** not be counted as untested code.
    497 */
    498 #if defined(SQLITE_COVERAGE_TEST)
    499 # define ALWAYS(X)      (1)
    500 # define NEVER(X)       (0)
    501 #elif !defined(NDEBUG)
    502 # define ALWAYS(X)      ((X)?1:(assert(0),0))
    503 # define NEVER(X)       ((X)?(assert(0),1):0)
    504 #else
    505 # define ALWAYS(X)      (X)
    506 # define NEVER(X)       (X)
    507 #endif
    508 
    509 /*
    510 ** The macro unlikely() is a hint that surrounds a boolean
    511 ** expression that is usually false.  Macro likely() surrounds
    512 ** a boolean expression that is usually true.  GCC is able to
    513 ** use these hints to generate better code, sometimes.
    514 */
    515 #if defined(__GNUC__) && 0
    516 # define likely(X)    __builtin_expect((X),1)
    517 # define unlikely(X)  __builtin_expect((X),0)
    518 #else
    519 # define likely(X)    !!(X)
    520 # define unlikely(X)  !!(X)
    521 #endif
    522 
    523 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
    524 /************** Begin file sqlite3.h *****************************************/
    525 /*
    526 ** 2001 September 15
    527 **
    528 ** The author disclaims copyright to this source code.  In place of
    529 ** a legal notice, here is a blessing:
    530 **
    531 **    May you do good and not evil.
    532 **    May you find forgiveness for yourself and forgive others.
    533 **    May you share freely, never taking more than you give.
    534 **
    535 *************************************************************************
    536 ** This header file defines the interface that the SQLite library
    537 ** presents to client programs.  If a C-function, structure, datatype,
    538 ** or constant definition does not appear in this file, then it is
    539 ** not a published API of SQLite, is subject to change without
    540 ** notice, and should not be referenced by programs that use SQLite.
    541 **
    542 ** Some of the definitions that are in this file are marked as
    543 ** "experimental".  Experimental interfaces are normally new
    544 ** features recently added to SQLite.  We do not anticipate changes
    545 ** to experimental interfaces but reserve the right to make minor changes
    546 ** if experience from use "in the wild" suggest such changes are prudent.
    547 **
    548 ** The official C-language API documentation for SQLite is derived
    549 ** from comments in this file.  This file is the authoritative source
    550 ** on how SQLite interfaces are suppose to operate.
    551 **
    552 ** The name of this file under configuration management is "sqlite.h.in".
    553 ** The makefile makes some minor changes to this file (such as inserting
    554 ** the version number) and changes its name to "sqlite3.h" as
    555 ** part of the build process.
    556 */
    557 #ifndef _SQLITE3_H_
    558 #define _SQLITE3_H_
    559 #include <stdarg.h>     /* Needed for the definition of va_list */
    560 
    561 /*
    562 ** Make sure we can call this stuff from C++.
    563 */
    564 #if 0
    565 extern "C" {
    566 #endif
    567 
    568 
    569 /*
    570 ** Add the ability to override 'extern'
    571 */
    572 #ifndef SQLITE_EXTERN
    573 # define SQLITE_EXTERN extern
    574 #endif
    575 
    576 #ifndef SQLITE_API
    577 # define SQLITE_API
    578 #endif
    579 
    580 
    581 /*
    582 ** These no-op macros are used in front of interfaces to mark those
    583 ** interfaces as either deprecated or experimental.  New applications
    584 ** should not use deprecated interfaces - they are support for backwards
    585 ** compatibility only.  Application writers should be aware that
    586 ** experimental interfaces are subject to change in point releases.
    587 **
    588 ** These macros used to resolve to various kinds of compiler magic that
    589 ** would generate warning messages when they were used.  But that
    590 ** compiler magic ended up generating such a flurry of bug reports
    591 ** that we have taken it all out and gone back to using simple
    592 ** noop macros.
    593 */
    594 #define SQLITE_DEPRECATED
    595 #define SQLITE_EXPERIMENTAL
    596 
    597 /*
    598 ** Ensure these symbols were not defined by some previous header file.
    599 */
    600 #ifdef SQLITE_VERSION
    601 # undef SQLITE_VERSION
    602 #endif
    603 #ifdef SQLITE_VERSION_NUMBER
    604 # undef SQLITE_VERSION_NUMBER
    605 #endif
    606 
    607 /*
    608 ** CAPI3REF: Compile-Time Library Version Numbers
    609 **
    610 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
    611 ** evaluates to a string literal that is the SQLite version in the
    612 ** format "X.Y.Z" where X is the major version number (always 3 for
    613 ** SQLite3) and Y is the minor version number and Z is the release number.)^
    614 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
    615 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
    616 ** numbers used in [SQLITE_VERSION].)^
    617 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
    618 ** be larger than the release from which it is derived.  Either Y will
    619 ** be held constant and Z will be incremented or else Y will be incremented
    620 ** and Z will be reset to zero.
    621 **
    622 ** Since version 3.6.18, SQLite source code has been stored in the
    623 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
    624 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
    625 ** a string which identifies a particular check-in of SQLite
    626 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
    627 ** string contains the date and time of the check-in (UTC) and an SHA1
    628 ** hash of the entire source tree.
    629 **
    630 ** See also: [sqlite3_libversion()],
    631 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
    632 ** [sqlite_version()] and [sqlite_source_id()].
    633 */
    634 #define SQLITE_VERSION        "3.6.22"
    635 #define SQLITE_VERSION_NUMBER 3006022
    636 #define SQLITE_SOURCE_ID      "2010-03-22 23:55:10 82dd61fccff3e4c77e060e5734cd4b4e2eeb7c32"
    637 
    638 /*
    639 ** CAPI3REF: Run-Time Library Version Numbers
    640 ** KEYWORDS: sqlite3_version
    641 **
    642 ** These interfaces provide the same information as the [SQLITE_VERSION],
    643 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
    644 ** but are associated with the library instead of the header file.  ^(Cautious
    645 ** programmers might include assert() statements in their application to
    646 ** verify that values returned by these interfaces match the macros in
    647 ** the header, and thus insure that the application is
    648 ** compiled with matching library and header files.
    649 **
    650 ** <blockquote><pre>
    651 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    652 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    653 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    654 ** </pre></blockquote>)^
    655 **
    656 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
    657 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
    658 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
    659 ** function is provided for use in DLLs since DLL users usually do not have
    660 ** direct access to string constants within the DLL.  ^The
    661 ** sqlite3_libversion_number() function returns an integer equal to
    662 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
    663 ** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
    664 ** C preprocessor macro.
    665 **
    666 ** See also: [sqlite_version()] and [sqlite_source_id()].
    667 */
    668 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
    669 SQLITE_API const char *sqlite3_libversion(void);
    670 SQLITE_API const char *sqlite3_sourceid(void);
    671 SQLITE_API int sqlite3_libversion_number(void);
    672 
    673 /*
    674 ** CAPI3REF: Test To See If The Library Is Threadsafe
    675 **
    676 ** ^The sqlite3_threadsafe() function returns zero if and only if
    677 ** SQLite was compiled mutexing code omitted due to the
    678 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
    679 **
    680 ** SQLite can be compiled with or without mutexes.  When
    681 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
    682 ** are enabled and SQLite is threadsafe.  When the
    683 ** [SQLITE_THREADSAFE] macro is 0,
    684 ** the mutexes are omitted.  Without the mutexes, it is not safe
    685 ** to use SQLite concurrently from more than one thread.
    686 **
    687 ** Enabling mutexes incurs a measurable performance penalty.
    688 ** So if speed is of utmost importance, it makes sense to disable
    689 ** the mutexes.  But for maximum safety, mutexes should be enabled.
    690 ** ^The default behavior is for mutexes to be enabled.
    691 **
    692 ** This interface can be used by an application to make sure that the
    693 ** version of SQLite that it is linking against was compiled with
    694 ** the desired setting of the [SQLITE_THREADSAFE] macro.
    695 **
    696 ** This interface only reports on the compile-time mutex setting
    697 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
    698 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
    699 ** can be fully or partially disabled using a call to [sqlite3_config()]
    700 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
    701 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
    702 ** sqlite3_threadsafe() function shows only the compile-time setting of
    703 ** thread safety, not any run-time changes to that setting made by
    704 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
    705 ** is unchanged by calls to sqlite3_config().)^
    706 **
    707 ** See the [threading mode] documentation for additional information.
    708 */
    709 SQLITE_API int sqlite3_threadsafe(void);
    710 
    711 /*
    712 ** CAPI3REF: Database Connection Handle
    713 ** KEYWORDS: {database connection} {database connections}
    714 **
    715 ** Each open SQLite database is represented by a pointer to an instance of
    716 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
    717 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
    718 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
    719 ** is its destructor.  There are many other interfaces (such as
    720 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
    721 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
    722 ** sqlite3 object.
    723 */
    724 typedef struct sqlite3 sqlite3;
    725 
    726 /*
    727 ** CAPI3REF: 64-Bit Integer Types
    728 ** KEYWORDS: sqlite_int64 sqlite_uint64
    729 **
    730 ** Because there is no cross-platform way to specify 64-bit integer types
    731 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
    732 **
    733 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
    734 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
    735 ** compatibility only.
    736 **
    737 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
    738 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
    739 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
    740 ** between 0 and +18446744073709551615 inclusive.
    741 */
    742 #ifdef SQLITE_INT64_TYPE
    743   typedef SQLITE_INT64_TYPE sqlite_int64;
    744   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
    745 #elif defined(_MSC_VER) || defined(__BORLANDC__)
    746   typedef __int64 sqlite_int64;
    747   typedef unsigned __int64 sqlite_uint64;
    748 #else
    749   typedef long long int sqlite_int64;
    750   typedef unsigned long long int sqlite_uint64;
    751 #endif
    752 typedef sqlite_int64 sqlite3_int64;
    753 typedef sqlite_uint64 sqlite3_uint64;
    754 
    755 /*
    756 ** If compiling for a processor that lacks floating point support,
    757 ** substitute integer for floating-point.
    758 */
    759 #ifdef SQLITE_OMIT_FLOATING_POINT
    760 # define double sqlite3_int64
    761 #endif
    762 
    763 /*
    764 ** CAPI3REF: Closing A Database Connection
    765 **
    766 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
    767 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
    768 ** successfullly destroyed and all associated resources are deallocated.
    769 **
    770 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
    771 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
    772 ** the [sqlite3] object prior to attempting to close the object.  ^If
    773 ** sqlite3_close() is called on a [database connection] that still has
    774 ** outstanding [prepared statements] or [BLOB handles], then it returns
    775 ** SQLITE_BUSY.
    776 **
    777 ** ^If [sqlite3_close()] is invoked while a transaction is open,
    778 ** the transaction is automatically rolled back.
    779 **
    780 ** The C parameter to [sqlite3_close(C)] must be either a NULL
    781 ** pointer or an [sqlite3] object pointer obtained
    782 ** from [sqlite3_open()], [sqlite3_open16()], or
    783 ** [sqlite3_open_v2()], and not previously closed.
    784 ** ^Calling sqlite3_close() with a NULL pointer argument is a
    785 ** harmless no-op.
    786 */
    787 SQLITE_API int sqlite3_close(sqlite3 *);
    788 
    789 /*
    790 ** The type for a callback function.
    791 ** This is legacy and deprecated.  It is included for historical
    792 ** compatibility and is not documented.
    793 */
    794 typedef int (*sqlite3_callback)(void*,int,char**, char**);
    795 
    796 /*
    797 ** CAPI3REF: One-Step Query Execution Interface
    798 **
    799 ** The sqlite3_exec() interface is a convenience wrapper around
    800 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
    801 ** that allows an application to run multiple statements of SQL
    802 ** without having to use a lot of C code.
    803 **
    804 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
    805 ** semicolon-separate SQL statements passed into its 2nd argument,
    806 ** in the context of the [database connection] passed in as its 1st
    807 ** argument.  ^If the callback function of the 3rd argument to
    808 ** sqlite3_exec() is not NULL, then it is invoked for each result row
    809 ** coming out of the evaluated SQL statements.  ^The 4th argument to
    810 ** to sqlite3_exec() is relayed through to the 1st argument of each
    811 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
    812 ** is NULL, then no callback is ever invoked and result rows are
    813 ** ignored.
    814 **
    815 ** ^If an error occurs while evaluating the SQL statements passed into
    816 ** sqlite3_exec(), then execution of the current statement stops and
    817 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
    818 ** is not NULL then any error message is written into memory obtained
    819 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
    820 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
    821 ** on error message strings returned through the 5th parameter of
    822 ** of sqlite3_exec() after the error message string is no longer needed.
    823 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
    824 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
    825 ** NULL before returning.
    826 **
    827 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
    828 ** routine returns SQLITE_ABORT without invoking the callback again and
    829 ** without running any subsequent SQL statements.
    830 **
    831 ** ^The 2nd argument to the sqlite3_exec() callback function is the
    832 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
    833 ** callback is an array of pointers to strings obtained as if from
    834 ** [sqlite3_column_text()], one for each column.  ^If an element of a
    835 ** result row is NULL then the corresponding string pointer for the
    836 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
    837 ** sqlite3_exec() callback is an array of pointers to strings where each
    838 ** entry represents the name of corresponding result column as obtained
    839 ** from [sqlite3_column_name()].
    840 **
    841 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
    842 ** to an empty string, or a pointer that contains only whitespace and/or
    843 ** SQL comments, then no SQL statements are evaluated and the database
    844 ** is not changed.
    845 **
    846 ** Restrictions:
    847 **
    848 ** <ul>
    849 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
    850 **      is a valid and open [database connection].
    851 ** <li> The application must not close [database connection] specified by
    852 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
    853 ** <li> The application must not modify the SQL statement text passed into
    854 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
    855 ** </ul>
    856 */
    857 SQLITE_API int sqlite3_exec(
    858   sqlite3*,                                  /* An open database */
    859   const char *sql,                           /* SQL to be evaluated */
    860   int (*callback)(void*,int,char**,char**),  /* Callback function */
    861   void *,                                    /* 1st argument to callback */
    862   char **errmsg                              /* Error msg written here */
    863 );
    864 
    865 /*
    866 ** CAPI3REF: Result Codes
    867 ** KEYWORDS: SQLITE_OK {error code} {error codes}
    868 ** KEYWORDS: {result code} {result codes}
    869 **
    870 ** Many SQLite functions return an integer result code from the set shown
    871 ** here in order to indicates success or failure.
    872 **
    873 ** New error codes may be added in future versions of SQLite.
    874 **
    875 ** See also: [SQLITE_IOERR_READ | extended result codes]
    876 */
    877 #define SQLITE_OK           0   /* Successful result */
    878 /* beginning-of-error-codes */
    879 #define SQLITE_ERROR        1   /* SQL error or missing database */
    880 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
    881 #define SQLITE_PERM         3   /* Access permission denied */
    882 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
    883 #define SQLITE_BUSY         5   /* The database file is locked */
    884 #define SQLITE_LOCKED       6   /* A table in the database is locked */
    885 #define SQLITE_NOMEM        7   /* A malloc() failed */
    886 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
    887 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
    888 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
    889 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
    890 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
    891 #define SQLITE_FULL        13   /* Insertion failed because database is full */
    892 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
    893 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
    894 #define SQLITE_EMPTY       16   /* Database is empty */
    895 #define SQLITE_SCHEMA      17   /* The database schema changed */
    896 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
    897 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
    898 #define SQLITE_MISMATCH    20   /* Data type mismatch */
    899 #define SQLITE_MISUSE      21   /* Library used incorrectly */
    900 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
    901 #define SQLITE_AUTH        23   /* Authorization denied */
    902 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
    903 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
    904 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
    905 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
    906 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
    907 /* end-of-error-codes */
    908 
    909 /*
    910 ** CAPI3REF: Extended Result Codes
    911 ** KEYWORDS: {extended error code} {extended error codes}
    912 ** KEYWORDS: {extended result code} {extended result codes}
    913 **
    914 ** In its default configuration, SQLite API routines return one of 26 integer
    915 ** [SQLITE_OK | result codes].  However, experience has shown that many of
    916 ** these result codes are too coarse-grained.  They do not provide as
    917 ** much information about problems as programmers might like.  In an effort to
    918 ** address this, newer versions of SQLite (version 3.3.8 and later) include
    919 ** support for additional result codes that provide more detailed information
    920 ** about errors. The extended result codes are enabled or disabled
    921 ** on a per database connection basis using the
    922 ** [sqlite3_extended_result_codes()] API.
    923 **
    924 ** Some of the available extended result codes are listed here.
    925 ** One may expect the number of extended result codes will be expand
    926 ** over time.  Software that uses extended result codes should expect
    927 ** to see new result codes in future releases of SQLite.
    928 **
    929 ** The SQLITE_OK result code will never be extended.  It will always
    930 ** be exactly zero.
    931 */
    932 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
    933 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
    934 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
    935 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
    936 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
    937 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
    938 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
    939 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
    940 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
    941 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
    942 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
    943 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
    944 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
    945 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
    946 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
    947 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
    948 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
    949 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
    950 
    951 /*
    952 ** CAPI3REF: Flags For File Open Operations
    953 **
    954 ** These bit values are intended for use in the
    955 ** 3rd parameter to the [sqlite3_open_v2()] interface and
    956 ** in the 4th parameter to the xOpen method of the
    957 ** [sqlite3_vfs] object.
    958 */
    959 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
    960 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
    961 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
    962 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
    963 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
    964 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
    965 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
    966 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
    967 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
    968 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
    969 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
    970 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
    971 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
    972 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
    973 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
    974 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
    975 
    976 /*
    977 ** CAPI3REF: Device Characteristics
    978 **
    979 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
    980 ** object returns an integer which is a vector of the these
    981 ** bit values expressing I/O characteristics of the mass storage
    982 ** device that holds the file that the [sqlite3_io_methods]
    983 ** refers to.
    984 **
    985 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
    986 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
    987 ** mean that writes of blocks that are nnn bytes in size and
    988 ** are aligned to an address which is an integer multiple of
    989 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
    990 ** that when data is appended to a file, the data is appended
    991 ** first then the size of the file is extended, never the other
    992 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
    993 ** information is written to disk in the same order as calls
    994 ** to xWrite().
    995 */
    996 #define SQLITE_IOCAP_ATOMIC          0x00000001
    997 #define SQLITE_IOCAP_ATOMIC512       0x00000002
    998 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
    999 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
   1000 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
   1001 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
   1002 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
   1003 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
   1004 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
   1005 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
   1006 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
   1007 
   1008 /*
   1009 ** CAPI3REF: File Locking Levels
   1010 **
   1011 ** SQLite uses one of these integer values as the second
   1012 ** argument to calls it makes to the xLock() and xUnlock() methods
   1013 ** of an [sqlite3_io_methods] object.
   1014 */
   1015 #define SQLITE_LOCK_NONE          0
   1016 #define SQLITE_LOCK_SHARED        1
   1017 #define SQLITE_LOCK_RESERVED      2
   1018 #define SQLITE_LOCK_PENDING       3
   1019 #define SQLITE_LOCK_EXCLUSIVE     4
   1020 
   1021 /*
   1022 ** CAPI3REF: Synchronization Type Flags
   1023 **
   1024 ** When SQLite invokes the xSync() method of an
   1025 ** [sqlite3_io_methods] object it uses a combination of
   1026 ** these integer values as the second argument.
   1027 **
   1028 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1029 ** sync operation only needs to flush data to mass storage.  Inode
   1030 ** information need not be flushed. If the lower four bits of the flag
   1031 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1032 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1033 ** to use Mac OS X style fullsync instead of fsync().
   1034 */
   1035 #define SQLITE_SYNC_NORMAL        0x00002
   1036 #define SQLITE_SYNC_FULL          0x00003
   1037 #define SQLITE_SYNC_DATAONLY      0x00010
   1038 
   1039 /*
   1040 ** CAPI3REF: OS Interface Open File Handle
   1041 **
   1042 ** An [sqlite3_file] object represents an open file in the
   1043 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1044 ** implementations will
   1045 ** want to subclass this object by appending additional fields
   1046 ** for their own use.  The pMethods entry is a pointer to an
   1047 ** [sqlite3_io_methods] object that defines methods for performing
   1048 ** I/O operations on the open file.
   1049 */
   1050 typedef struct sqlite3_file sqlite3_file;
   1051 struct sqlite3_file {
   1052   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1053 };
   1054 
   1055 /*
   1056 ** CAPI3REF: OS Interface File Virtual Methods Object
   1057 **
   1058 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
   1059 ** [sqlite3_file] object (or, more commonly, a subclass of the
   1060 ** [sqlite3_file] object) with a pointer to an instance of this object.
   1061 ** This object defines the methods used to perform various operations
   1062 ** against the open file represented by the [sqlite3_file] object.
   1063 **
   1064 ** If the xOpen method sets the sqlite3_file.pMethods element
   1065 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1066 ** may be invoked even if the xOpen reported that it failed.  The
   1067 ** only way to prevent a call to xClose following a failed xOpen
   1068 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
   1069 **
   1070 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1071 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1072 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1073 ** flag may be ORed in to indicate that only the data of the file
   1074 ** and not its inode needs to be synced.
   1075 **
   1076 ** The integer values to xLock() and xUnlock() are one of
   1077 ** <ul>
   1078 ** <li> [SQLITE_LOCK_NONE],
   1079 ** <li> [SQLITE_LOCK_SHARED],
   1080 ** <li> [SQLITE_LOCK_RESERVED],
   1081 ** <li> [SQLITE_LOCK_PENDING], or
   1082 ** <li> [SQLITE_LOCK_EXCLUSIVE].
   1083 ** </ul>
   1084 ** xLock() increases the lock. xUnlock() decreases the lock.
   1085 ** The xCheckReservedLock() method checks whether any database connection,
   1086 ** either in this process or in some other process, is holding a RESERVED,
   1087 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1088 ** if such a lock exists and false otherwise.
   1089 **
   1090 ** The xFileControl() method is a generic interface that allows custom
   1091 ** VFS implementations to directly control an open file using the
   1092 ** [sqlite3_file_control()] interface.  The second "op" argument is an
   1093 ** integer opcode.  The third argument is a generic pointer intended to
   1094 ** point to a structure that may contain arguments or space in which to
   1095 ** write return values.  Potential uses for xFileControl() might be
   1096 ** functions to enable blocking locks with timeouts, to change the
   1097 ** locking strategy (for example to use dot-file locks), to inquire
   1098 ** about the status of a lock, or to break stale locks.  The SQLite
   1099 ** core reserves all opcodes less than 100 for its own use.
   1100 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   1101 ** Applications that define a custom xFileControl method should use opcodes
   1102 ** greater than 100 to avoid conflicts.
   1103 **
   1104 ** The xSectorSize() method returns the sector size of the
   1105 ** device that underlies the file.  The sector size is the
   1106 ** minimum write that can be performed without disturbing
   1107 ** other bytes in the file.  The xDeviceCharacteristics()
   1108 ** method returns a bit vector describing behaviors of the
   1109 ** underlying device:
   1110 **
   1111 ** <ul>
   1112 ** <li> [SQLITE_IOCAP_ATOMIC]
   1113 ** <li> [SQLITE_IOCAP_ATOMIC512]
   1114 ** <li> [SQLITE_IOCAP_ATOMIC1K]
   1115 ** <li> [SQLITE_IOCAP_ATOMIC2K]
   1116 ** <li> [SQLITE_IOCAP_ATOMIC4K]
   1117 ** <li> [SQLITE_IOCAP_ATOMIC8K]
   1118 ** <li> [SQLITE_IOCAP_ATOMIC16K]
   1119 ** <li> [SQLITE_IOCAP_ATOMIC32K]
   1120 ** <li> [SQLITE_IOCAP_ATOMIC64K]
   1121 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1122 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1123 ** </ul>
   1124 **
   1125 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1126 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1127 ** mean that writes of blocks that are nnn bytes in size and
   1128 ** are aligned to an address which is an integer multiple of
   1129 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1130 ** that when data is appended to a file, the data is appended
   1131 ** first then the size of the file is extended, never the other
   1132 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1133 ** information is written to disk in the same order as calls
   1134 ** to xWrite().
   1135 **
   1136 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1137 ** in the unread portions of the buffer with zeros.  A VFS that
   1138 ** fails to zero-fill short reads might seem to work.  However,
   1139 ** failure to zero-fill short reads will eventually lead to
   1140 ** database corruption.
   1141 */
   1142 typedef struct sqlite3_io_methods sqlite3_io_methods;
   1143 struct sqlite3_io_methods {
   1144   int iVersion;
   1145   int (*xClose)(sqlite3_file*);
   1146   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1147   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1148   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1149   int (*xSync)(sqlite3_file*, int flags);
   1150   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1151   int (*xLock)(sqlite3_file*, int);
   1152   int (*xUnlock)(sqlite3_file*, int);
   1153   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1154   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1155   int (*xSectorSize)(sqlite3_file*);
   1156   int (*xDeviceCharacteristics)(sqlite3_file*);
   1157   /* Additional methods may be added in future releases */
   1158 };
   1159 
   1160 /*
   1161 ** CAPI3REF: Standard File Control Opcodes
   1162 **
   1163 ** These integer constants are opcodes for the xFileControl method
   1164 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1165 ** interface.
   1166 **
   1167 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1168 ** opcode causes the xFileControl method to write the current state of
   1169 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1170 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1171 ** into an integer that the pArg argument points to. This capability
   1172 ** is used during testing and only needs to be supported when SQLITE_TEST
   1173 ** is defined.
   1174 */
   1175 #define SQLITE_FCNTL_LOCKSTATE        1
   1176 #define SQLITE_GET_LOCKPROXYFILE      2
   1177 #define SQLITE_SET_LOCKPROXYFILE      3
   1178 #define SQLITE_LAST_ERRNO             4
   1179 
   1180 /*
   1181 ** CAPI3REF: Mutex Handle
   1182 **
   1183 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   1184 ** abstract type for a mutex object.  The SQLite core never looks
   1185 ** at the internal representation of an [sqlite3_mutex].  It only
   1186 ** deals with pointers to the [sqlite3_mutex] object.
   1187 **
   1188 ** Mutexes are created using [sqlite3_mutex_alloc()].
   1189 */
   1190 typedef struct sqlite3_mutex sqlite3_mutex;
   1191 
   1192 /*
   1193 ** CAPI3REF: OS Interface Object
   1194 **
   1195 ** An instance of the sqlite3_vfs object defines the interface between
   1196 ** the SQLite core and the underlying operating system.  The "vfs"
   1197 ** in the name of the object stands for "virtual file system".
   1198 **
   1199 ** The value of the iVersion field is initially 1 but may be larger in
   1200 ** future versions of SQLite.  Additional fields may be appended to this
   1201 ** object when the iVersion value is increased.  Note that the structure
   1202 ** of the sqlite3_vfs object changes in the transaction between
   1203 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
   1204 ** modified.
   1205 **
   1206 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   1207 ** structure used by this VFS.  mxPathname is the maximum length of
   1208 ** a pathname in this VFS.
   1209 **
   1210 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   1211 ** the pNext pointer.  The [sqlite3_vfs_register()]
   1212 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   1213 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   1214 ** searches the list.  Neither the application code nor the VFS
   1215 ** implementation should use the pNext pointer.
   1216 **
   1217 ** The pNext field is the only field in the sqlite3_vfs
   1218 ** structure that SQLite will ever modify.  SQLite will only access
   1219 ** or modify this field while holding a particular static mutex.
   1220 ** The application should never modify anything within the sqlite3_vfs
   1221 ** object once the object has been registered.
   1222 **
   1223 ** The zName field holds the name of the VFS module.  The name must
   1224 ** be unique across all VFS modules.
   1225 **
   1226 ** SQLite will guarantee that the zFilename parameter to xOpen
   1227 ** is either a NULL pointer or string obtained
   1228 ** from xFullPathname().  SQLite further guarantees that
   1229 ** the string will be valid and unchanged until xClose() is
   1230 ** called. Because of the previous sentence,
   1231 ** the [sqlite3_file] can safely store a pointer to the
   1232 ** filename if it needs to remember the filename for some reason.
   1233 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
   1234 ** must invent its own temporary name for the file.  Whenever the
   1235 ** xFilename parameter is NULL it will also be the case that the
   1236 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   1237 **
   1238 ** The flags argument to xOpen() includes all bits set in
   1239 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   1240 ** or [sqlite3_open16()] is used, then flags includes at least
   1241 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   1242 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   1243 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   1244 **
   1245 ** SQLite will also add one of the following flags to the xOpen()
   1246 ** call, depending on the object being opened:
   1247 **
   1248 ** <ul>
   1249 ** <li>  [SQLITE_OPEN_MAIN_DB]
   1250 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   1251 ** <li>  [SQLITE_OPEN_TEMP_DB]
   1252 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   1253 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   1254 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   1255 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   1256 ** </ul>
   1257 **
   1258 ** The file I/O implementation can use the object type flags to
   1259 ** change the way it deals with files.  For example, an application
   1260 ** that does not care about crash recovery or rollback might make
   1261 ** the open of a journal file a no-op.  Writes to this journal would
   1262 ** also be no-ops, and any attempt to read the journal would return
   1263 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   1264 ** file will be doing page-aligned sector reads and writes in a random
   1265 ** order and set up its I/O subsystem accordingly.
   1266 **
   1267 ** SQLite might also add one of the following flags to the xOpen method:
   1268 **
   1269 ** <ul>
   1270 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   1271 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   1272 ** </ul>
   1273 **
   1274 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   1275 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
   1276 ** will be set for TEMP  databases, journals and for subjournals.
   1277 **
   1278 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   1279 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   1280 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   1281 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   1282 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   1283 ** be created, and that it is an error if it already exists.
   1284 ** It is <i>not</i> used to indicate the file should be opened
   1285 ** for exclusive access.
   1286 **
   1287 ** At least szOsFile bytes of memory are allocated by SQLite
   1288 ** to hold the  [sqlite3_file] structure passed as the third
   1289 ** argument to xOpen.  The xOpen method does not have to
   1290 ** allocate the structure; it should just fill it in.  Note that
   1291 ** the xOpen method must set the sqlite3_file.pMethods to either
   1292 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   1293 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   1294 ** element will be valid after xOpen returns regardless of the success
   1295 ** or failure of the xOpen call.
   1296 **
   1297 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   1298 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   1299 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   1300 ** to test whether a file is at least readable.   The file can be a
   1301 ** directory.
   1302 **
   1303 ** SQLite will always allocate at least mxPathname+1 bytes for the
   1304 ** output buffer xFullPathname.  The exact size of the output buffer
   1305 ** is also passed as a parameter to both  methods. If the output buffer
   1306 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   1307 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   1308 ** to prevent this by setting mxPathname to a sufficiently large value.
   1309 **
   1310 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
   1311 ** are not strictly a part of the filesystem, but they are
   1312 ** included in the VFS structure for completeness.
   1313 ** The xRandomness() function attempts to return nBytes bytes
   1314 ** of good-quality randomness into zOut.  The return value is
   1315 ** the actual number of bytes of randomness obtained.
   1316 ** The xSleep() method causes the calling thread to sleep for at
   1317 ** least the number of microseconds given.  The xCurrentTime()
   1318 ** method returns a Julian Day Number for the current date and time.
   1319 **
   1320 */
   1321 typedef struct sqlite3_vfs sqlite3_vfs;
   1322 struct sqlite3_vfs {
   1323   int iVersion;            /* Structure version number */
   1324   int szOsFile;            /* Size of subclassed sqlite3_file */
   1325   int mxPathname;          /* Maximum file pathname length */
   1326   sqlite3_vfs *pNext;      /* Next registered VFS */
   1327   const char *zName;       /* Name of this virtual file system */
   1328   void *pAppData;          /* Pointer to application-specific data */
   1329   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   1330                int flags, int *pOutFlags);
   1331   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   1332   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   1333   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   1334   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   1335   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   1336   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   1337   void (*xDlClose)(sqlite3_vfs*, void*);
   1338   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   1339   int (*xSleep)(sqlite3_vfs*, int microseconds);
   1340   int (*xCurrentTime)(sqlite3_vfs*, double*);
   1341   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   1342   /* New fields may be appended in figure versions.  The iVersion
   1343   ** value will increment whenever this happens. */
   1344 };
   1345 
   1346 /*
   1347 ** CAPI3REF: Flags for the xAccess VFS method
   1348 **
   1349 ** These integer constants can be used as the third parameter to
   1350 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   1351 ** what kind of permissions the xAccess method is looking for.
   1352 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   1353 ** simply checks whether the file exists.
   1354 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   1355 ** checks whether the file is both readable and writable.
   1356 ** With SQLITE_ACCESS_READ, the xAccess method
   1357 ** checks whether the file is readable.
   1358 */
   1359 #define SQLITE_ACCESS_EXISTS    0
   1360 #define SQLITE_ACCESS_READWRITE 1
   1361 #define SQLITE_ACCESS_READ      2
   1362 
   1363 /*
   1364 ** CAPI3REF: Initialize The SQLite Library
   1365 **
   1366 ** ^The sqlite3_initialize() routine initializes the
   1367 ** SQLite library.  ^The sqlite3_shutdown() routine
   1368 ** deallocates any resources that were allocated by sqlite3_initialize().
   1369 ** These routines are designed to aid in process initialization and
   1370 ** shutdown on embedded systems.  Workstation applications using
   1371 ** SQLite normally do not need to invoke either of these routines.
   1372 **
   1373 ** A call to sqlite3_initialize() is an "effective" call if it is
   1374 ** the first time sqlite3_initialize() is invoked during the lifetime of
   1375 ** the process, or if it is the first time sqlite3_initialize() is invoked
   1376 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   1377 ** of sqlite3_initialize() does any initialization.  All other calls
   1378 ** are harmless no-ops.)^
   1379 **
   1380 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   1381 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   1382 ** an effective call to sqlite3_shutdown() does any deinitialization.
   1383 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   1384 **
   1385 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   1386 ** is not.  The sqlite3_shutdown() interface must only be called from a
   1387 ** single thread.  All open [database connections] must be closed and all
   1388 ** other SQLite resources must be deallocated prior to invoking
   1389 ** sqlite3_shutdown().
   1390 **
   1391 ** Among other things, ^sqlite3_initialize() will invoke
   1392 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   1393 ** will invoke sqlite3_os_end().
   1394 **
   1395 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   1396 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   1397 ** the library (perhaps it is unable to allocate a needed resource such
   1398 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   1399 **
   1400 ** ^The sqlite3_initialize() routine is called internally by many other
   1401 ** SQLite interfaces so that an application usually does not need to
   1402 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   1403 ** calls sqlite3_initialize() so the SQLite library will be automatically
   1404 ** initialized when [sqlite3_open()] is called if it has not be initialized
   1405 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   1406 ** compile-time option, then the automatic calls to sqlite3_initialize()
   1407 ** are omitted and the application must call sqlite3_initialize() directly
   1408 ** prior to using any other SQLite interface.  For maximum portability,
   1409 ** it is recommended that applications always invoke sqlite3_initialize()
   1410 ** directly prior to using any other SQLite interface.  Future releases
   1411 ** of SQLite may require this.  In other words, the behavior exhibited
   1412 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   1413 ** default behavior in some future release of SQLite.
   1414 **
   1415 ** The sqlite3_os_init() routine does operating-system specific
   1416 ** initialization of the SQLite library.  The sqlite3_os_end()
   1417 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   1418 ** performed by these routines include allocation or deallocation
   1419 ** of static resources, initialization of global variables,
   1420 ** setting up a default [sqlite3_vfs] module, or setting up
   1421 ** a default configuration using [sqlite3_config()].
   1422 **
   1423 ** The application should never invoke either sqlite3_os_init()
   1424 ** or sqlite3_os_end() directly.  The application should only invoke
   1425 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   1426 ** interface is called automatically by sqlite3_initialize() and
   1427 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   1428 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   1429 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   1430 ** When [custom builds | built for other platforms]
   1431 ** (using the [SQLITE_OS_OTHER=1] compile-time
   1432 ** option) the application must supply a suitable implementation for
   1433 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   1434 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   1435 ** must return [SQLITE_OK] on success and some other [error code] upon
   1436 ** failure.
   1437 */
   1438 SQLITE_API int sqlite3_initialize(void);
   1439 SQLITE_API int sqlite3_shutdown(void);
   1440 SQLITE_API int sqlite3_os_init(void);
   1441 SQLITE_API int sqlite3_os_end(void);
   1442 
   1443 /*
   1444 ** CAPI3REF: Configuring The SQLite Library
   1445 **
   1446 ** The sqlite3_config() interface is used to make global configuration
   1447 ** changes to SQLite in order to tune SQLite to the specific needs of
   1448 ** the application.  The default configuration is recommended for most
   1449 ** applications and so this routine is usually not necessary.  It is
   1450 ** provided to support rare applications with unusual needs.
   1451 **
   1452 ** The sqlite3_config() interface is not threadsafe.  The application
   1453 ** must insure that no other SQLite interfaces are invoked by other
   1454 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
   1455 ** may only be invoked prior to library initialization using
   1456 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   1457 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   1458 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   1459 ** Note, however, that ^sqlite3_config() can be called as part of the
   1460 ** implementation of an application-defined [sqlite3_os_init()].
   1461 **
   1462 ** The first argument to sqlite3_config() is an integer
   1463 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
   1464 ** what property of SQLite is to be configured.  Subsequent arguments
   1465 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
   1466 ** in the first argument.
   1467 **
   1468 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   1469 ** ^If the option is unknown or SQLite is unable to set the option
   1470 ** then this routine returns a non-zero [error code].
   1471 */
   1472 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
   1473 
   1474 /*
   1475 ** CAPI3REF: Configure database connections
   1476 ** EXPERIMENTAL
   1477 **
   1478 ** The sqlite3_db_config() interface is used to make configuration
   1479 ** changes to a [database connection].  The interface is similar to
   1480 ** [sqlite3_config()] except that the changes apply to a single
   1481 ** [database connection] (specified in the first argument).  The
   1482 ** sqlite3_db_config() interface should only be used immediately after
   1483 ** the database connection is created using [sqlite3_open()],
   1484 ** [sqlite3_open16()], or [sqlite3_open_v2()].
   1485 **
   1486 ** The second argument to sqlite3_db_config(D,V,...)  is the
   1487 ** configuration verb - an integer code that indicates what
   1488 ** aspect of the [database connection] is being configured.
   1489 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
   1490 ** New verbs are likely to be added in future releases of SQLite.
   1491 ** Additional arguments depend on the verb.
   1492 **
   1493 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   1494 ** the call is considered successful.
   1495 */
   1496 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
   1497 
   1498 /*
   1499 ** CAPI3REF: Memory Allocation Routines
   1500 ** EXPERIMENTAL
   1501 **
   1502 ** An instance of this object defines the interface between SQLite
   1503 ** and low-level memory allocation routines.
   1504 **
   1505 ** This object is used in only one place in the SQLite interface.
   1506 ** A pointer to an instance of this object is the argument to
   1507 ** [sqlite3_config()] when the configuration option is
   1508 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   1509 ** By creating an instance of this object
   1510 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   1511 ** during configuration, an application can specify an alternative
   1512 ** memory allocation subsystem for SQLite to use for all of its
   1513 ** dynamic memory needs.
   1514 **
   1515 ** Note that SQLite comes with several [built-in memory allocators]
   1516 ** that are perfectly adequate for the overwhelming majority of applications
   1517 ** and that this object is only useful to a tiny minority of applications
   1518 ** with specialized memory allocation requirements.  This object is
   1519 ** also used during testing of SQLite in order to specify an alternative
   1520 ** memory allocator that simulates memory out-of-memory conditions in
   1521 ** order to verify that SQLite recovers gracefully from such
   1522 ** conditions.
   1523 **
   1524 ** The xMalloc and xFree methods must work like the
   1525 ** malloc() and free() functions from the standard C library.
   1526 ** The xRealloc method must work like realloc() from the standard C library
   1527 ** with the exception that if the second argument to xRealloc is zero,
   1528 ** xRealloc must be a no-op - it must not perform any allocation or
   1529 ** deallocation.  ^SQLite guarantees that the second argument to
   1530 ** xRealloc is always a value returned by a prior call to xRoundup.
   1531 ** And so in cases where xRoundup always returns a positive number,
   1532 ** xRealloc can perform exactly as the standard library realloc() and
   1533 ** still be in compliance with this specification.
   1534 **
   1535 ** xSize should return the allocated size of a memory allocation
   1536 ** previously obtained from xMalloc or xRealloc.  The allocated size
   1537 ** is always at least as big as the requested size but may be larger.
   1538 **
   1539 ** The xRoundup method returns what would be the allocated size of
   1540 ** a memory allocation given a particular requested size.  Most memory
   1541 ** allocators round up memory allocations at least to the next multiple
   1542 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   1543 ** Every memory allocation request coming in through [sqlite3_malloc()]
   1544 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   1545 ** that causes the corresponding memory allocation to fail.
   1546 **
   1547 ** The xInit method initializes the memory allocator.  (For example,
   1548 ** it might allocate any require mutexes or initialize internal data
   1549 ** structures.  The xShutdown method is invoked (indirectly) by
   1550 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   1551 ** by xInit.  The pAppData pointer is used as the only parameter to
   1552 ** xInit and xShutdown.
   1553 **
   1554 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   1555 ** the xInit method, so the xInit method need not be threadsafe.  The
   1556 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   1557 ** not need to be threadsafe either.  For all other methods, SQLite
   1558 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   1559 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   1560 ** it is by default) and so the methods are automatically serialized.
   1561 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   1562 ** methods must be threadsafe or else make their own arrangements for
   1563 ** serialization.
   1564 **
   1565 ** SQLite will never invoke xInit() more than once without an intervening
   1566 ** call to xShutdown().
   1567 */
   1568 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   1569 struct sqlite3_mem_methods {
   1570   void *(*xMalloc)(int);         /* Memory allocation function */
   1571   void (*xFree)(void*);          /* Free a prior allocation */
   1572   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   1573   int (*xSize)(void*);           /* Return the size of an allocation */
   1574   int (*xRoundup)(int);          /* Round up request size to allocation size */
   1575   int (*xInit)(void*);           /* Initialize the memory allocator */
   1576   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   1577   void *pAppData;                /* Argument to xInit() and xShutdown() */
   1578 };
   1579 
   1580 /*
   1581 ** CAPI3REF: Configuration Options
   1582 ** EXPERIMENTAL
   1583 **
   1584 ** These constants are the available integer configuration options that
   1585 ** can be passed as the first argument to the [sqlite3_config()] interface.
   1586 **
   1587 ** New configuration options may be added in future releases of SQLite.
   1588 ** Existing configuration options might be discontinued.  Applications
   1589 ** should check the return code from [sqlite3_config()] to make sure that
   1590 ** the call worked.  The [sqlite3_config()] interface will return a
   1591 ** non-zero [error code] if a discontinued or unsupported configuration option
   1592 ** is invoked.
   1593 **
   1594 ** <dl>
   1595 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   1596 ** <dd>There are no arguments to this option.  ^This option sets the
   1597 ** [threading mode] to Single-thread.  In other words, it disables
   1598 ** all mutexing and puts SQLite into a mode where it can only be used
   1599 ** by a single thread.   ^If SQLite is compiled with
   1600 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1601 ** it is not possible to change the [threading mode] from its default
   1602 ** value of Single-thread and so [sqlite3_config()] will return
   1603 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   1604 ** configuration option.</dd>
   1605 **
   1606 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   1607 ** <dd>There are no arguments to this option.  ^This option sets the
   1608 ** [threading mode] to Multi-thread.  In other words, it disables
   1609 ** mutexing on [database connection] and [prepared statement] objects.
   1610 ** The application is responsible for serializing access to
   1611 ** [database connections] and [prepared statements].  But other mutexes
   1612 ** are enabled so that SQLite will be safe to use in a multi-threaded
   1613 ** environment as long as no two threads attempt to use the same
   1614 ** [database connection] at the same time.  ^If SQLite is compiled with
   1615 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1616 ** it is not possible to set the Multi-thread [threading mode] and
   1617 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1618 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   1619 **
   1620 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
   1621 ** <dd>There are no arguments to this option.  ^This option sets the
   1622 ** [threading mode] to Serialized. In other words, this option enables
   1623 ** all mutexes including the recursive
   1624 ** mutexes on [database connection] and [prepared statement] objects.
   1625 ** In this mode (which is the default when SQLite is compiled with
   1626 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   1627 ** to [database connections] and [prepared statements] so that the
   1628 ** application is free to use the same [database connection] or the
   1629 ** same [prepared statement] in different threads at the same time.
   1630 ** ^If SQLite is compiled with
   1631 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1632 ** it is not possible to set the Serialized [threading mode] and
   1633 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1634 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   1635 **
   1636 ** <dt>SQLITE_CONFIG_MALLOC</dt>
   1637 ** <dd> ^(This option takes a single argument which is a pointer to an
   1638 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
   1639 ** alternative low-level memory allocation routines to be used in place of
   1640 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   1641 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   1642 ** before the [sqlite3_config()] call returns.</dd>
   1643 **
   1644 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
   1645 ** <dd> ^(This option takes a single argument which is a pointer to an
   1646 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
   1647 ** structure is filled with the currently defined memory allocation routines.)^
   1648 ** This option can be used to overload the default memory allocation
   1649 ** routines with a wrapper that simulations memory allocation failure or
   1650 ** tracks memory usage, for example. </dd>
   1651 **
   1652 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   1653 ** <dd> ^This option takes single argument of type int, interpreted as a
   1654 ** boolean, which enables or disables the collection of memory allocation
   1655 ** statistics. ^(When memory allocation statistics are disabled, the
   1656 ** following SQLite interfaces become non-operational:
   1657 **   <ul>
   1658 **   <li> [sqlite3_memory_used()]
   1659 **   <li> [sqlite3_memory_highwater()]
   1660 **   <li> [sqlite3_soft_heap_limit()]
   1661 **   <li> [sqlite3_status()]
   1662 **   </ul>)^
   1663 ** ^Memory allocation statistics are enabled by default unless SQLite is
   1664 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   1665 ** allocation statistics are disabled by default.
   1666 ** </dd>
   1667 **
   1668 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
   1669 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1670 ** scratch memory.  There are three arguments:  A pointer an 8-byte
   1671 ** aligned memory buffer from which the scrach allocations will be
   1672 ** drawn, the size of each scratch allocation (sz),
   1673 ** and the maximum number of scratch allocations (N).  The sz
   1674 ** argument must be a multiple of 16. The sz parameter should be a few bytes
   1675 ** larger than the actual scratch space required due to internal overhead.
   1676 ** The first argument must be a pointer to an 8-byte aligned buffer
   1677 ** of at least sz*N bytes of memory.
   1678 ** ^SQLite will use no more than one scratch buffer per thread.  So
   1679 ** N should be set to the expected maximum number of threads.  ^SQLite will
   1680 ** never require a scratch buffer that is more than 6 times the database
   1681 ** page size. ^If SQLite needs needs additional scratch memory beyond
   1682 ** what is provided by this configuration option, then
   1683 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
   1684 **
   1685 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
   1686 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1687 ** the database page cache with the default page cache implemenation.
   1688 ** This configuration should not be used if an application-define page
   1689 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
   1690 ** There are three arguments to this option: A pointer to 8-byte aligned
   1691 ** memory, the size of each page buffer (sz), and the number of pages (N).
   1692 ** The sz argument should be the size of the largest database page
   1693 ** (a power of two between 512 and 32768) plus a little extra for each
   1694 ** page header.  ^The page header size is 20 to 40 bytes depending on
   1695 ** the host architecture.  ^It is harmless, apart from the wasted memory,
   1696 ** to make sz a little too large.  The first
   1697 ** argument should point to an allocation of at least sz*N bytes of memory.
   1698 ** ^SQLite will use the memory provided by the first argument to satisfy its
   1699 ** memory needs for the first N pages that it adds to cache.  ^If additional
   1700 ** page cache memory is needed beyond what is provided by this option, then
   1701 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
   1702 ** ^The implementation might use one or more of the N buffers to hold
   1703 ** memory accounting information. The pointer in the first argument must
   1704 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
   1705 ** will be undefined.</dd>
   1706 **
   1707 ** <dt>SQLITE_CONFIG_HEAP</dt>
   1708 ** <dd> ^This option specifies a static memory buffer that SQLite will use
   1709 ** for all of its dynamic memory allocation needs beyond those provided
   1710 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
   1711 ** There are three arguments: An 8-byte aligned pointer to the memory,
   1712 ** the number of bytes in the memory buffer, and the minimum allocation size.
   1713 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   1714 ** to using its default memory allocator (the system malloc() implementation),
   1715 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   1716 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
   1717 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
   1718 ** allocator is engaged to handle all of SQLites memory allocation needs.
   1719 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   1720 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
   1721 **
   1722 ** <dt>SQLITE_CONFIG_MUTEX</dt>
   1723 ** <dd> ^(This option takes a single argument which is a pointer to an
   1724 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
   1725 ** alternative low-level mutex routines to be used in place
   1726 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
   1727 ** content of the [sqlite3_mutex_methods] structure before the call to
   1728 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   1729 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1730 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1731 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   1732 ** return [SQLITE_ERROR].</dd>
   1733 **
   1734 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
   1735 ** <dd> ^(This option takes a single argument which is a pointer to an
   1736 ** instance of the [sqlite3_mutex_methods] structure.  The
   1737 ** [sqlite3_mutex_methods]
   1738 ** structure is filled with the currently defined mutex routines.)^
   1739 ** This option can be used to overload the default mutex allocation
   1740 ** routines with a wrapper used to track mutex usage for performance
   1741 ** profiling or testing, for example.   ^If SQLite is compiled with
   1742 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1743 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1744 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   1745 ** return [SQLITE_ERROR].</dd>
   1746 **
   1747 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   1748 ** <dd> ^(This option takes two arguments that determine the default
   1749 ** memory allocation for the lookaside memory allocator on each
   1750 ** [database connection].  The first argument is the
   1751 ** size of each lookaside buffer slot and the second is the number of
   1752 ** slots allocated to each database connection.)^  ^(This option sets the
   1753 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   1754 ** verb to [sqlite3_db_config()] can be used to change the lookaside
   1755 ** configuration on individual connections.)^ </dd>
   1756 **
   1757 ** <dt>SQLITE_CONFIG_PCACHE</dt>
   1758 ** <dd> ^(This option takes a single argument which is a pointer to
   1759 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
   1760 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
   1761 ** object and uses it for page cache memory allocations.</dd>
   1762 **
   1763 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
   1764 ** <dd> ^(This option takes a single argument which is a pointer to an
   1765 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
   1766 ** page cache implementation into that object.)^ </dd>
   1767 **
   1768 ** </dl>
   1769 */
   1770 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   1771 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   1772 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   1773 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   1774 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   1775 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
   1776 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   1777 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   1778 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   1779 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   1780 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   1781 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   1782 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   1783 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
   1784 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
   1785 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   1786 
   1787 /*
   1788 ** CAPI3REF: Configuration Options
   1789 ** EXPERIMENTAL
   1790 **
   1791 ** These constants are the available integer configuration options that
   1792 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   1793 **
   1794 ** New configuration options may be added in future releases of SQLite.
   1795 ** Existing configuration options might be discontinued.  Applications
   1796 ** should check the return code from [sqlite3_db_config()] to make sure that
   1797 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   1798 ** non-zero [error code] if a discontinued or unsupported configuration option
   1799 ** is invoked.
   1800 **
   1801 ** <dl>
   1802 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   1803 ** <dd> ^This option takes three additional arguments that determine the
   1804 ** [lookaside memory allocator] configuration for the [database connection].
   1805 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   1806 ** pointer to an memory buffer to use for lookaside memory.
   1807 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   1808 ** may be NULL in which case SQLite will allocate the
   1809 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   1810 ** size of each lookaside buffer slot.  ^The third argument is the number of
   1811 ** slots.  The size of the buffer in the first argument must be greater than
   1812 ** or equal to the product of the second and third arguments.  The buffer
   1813 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   1814 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   1815 ** rounded down to the next smaller
   1816 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
   1817 **
   1818 ** </dl>
   1819 */
   1820 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
   1821 
   1822 
   1823 /*
   1824 ** CAPI3REF: Enable Or Disable Extended Result Codes
   1825 **
   1826 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   1827 ** [extended result codes] feature of SQLite. ^The extended result
   1828 ** codes are disabled by default for historical compatibility.
   1829 */
   1830 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   1831 
   1832 /*
   1833 ** CAPI3REF: Last Insert Rowid
   1834 **
   1835 ** ^Each entry in an SQLite table has a unique 64-bit signed
   1836 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   1837 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   1838 ** names are not also used by explicitly declared columns. ^If
   1839 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   1840 ** is another alias for the rowid.
   1841 **
   1842 ** ^This routine returns the [rowid] of the most recent
   1843 ** successful [INSERT] into the database from the [database connection]
   1844 ** in the first argument.  ^If no successful [INSERT]s
   1845 ** have ever occurred on that database connection, zero is returned.
   1846 **
   1847 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
   1848 ** row is returned by this routine as long as the trigger is running.
   1849 ** But once the trigger terminates, the value returned by this routine
   1850 ** reverts to the last value inserted before the trigger fired.)^
   1851 **
   1852 ** ^An [INSERT] that fails due to a constraint violation is not a
   1853 ** successful [INSERT] and does not change the value returned by this
   1854 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   1855 ** and INSERT OR ABORT make no changes to the return value of this
   1856 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   1857 ** encounters a constraint violation, it does not fail.  The
   1858 ** INSERT continues to completion after deleting rows that caused
   1859 ** the constraint problem so INSERT OR REPLACE will always change
   1860 ** the return value of this interface.)^
   1861 **
   1862 ** ^For the purposes of this routine, an [INSERT] is considered to
   1863 ** be successful even if it is subsequently rolled back.
   1864 **
   1865 ** This function is accessible to SQL statements via the
   1866 ** [last_insert_rowid() SQL function].
   1867 **
   1868 ** If a separate thread performs a new [INSERT] on the same
   1869 ** database connection while the [sqlite3_last_insert_rowid()]
   1870 ** function is running and thus changes the last insert [rowid],
   1871 ** then the value returned by [sqlite3_last_insert_rowid()] is
   1872 ** unpredictable and might not equal either the old or the new
   1873 ** last insert [rowid].
   1874 */
   1875 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   1876 
   1877 /*
   1878 ** CAPI3REF: Count The Number Of Rows Modified
   1879 **
   1880 ** ^This function returns the number of database rows that were changed
   1881 ** or inserted or deleted by the most recently completed SQL statement
   1882 ** on the [database connection] specified by the first parameter.
   1883 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
   1884 ** or [DELETE] statement are counted.  Auxiliary changes caused by
   1885 ** triggers or [foreign key actions] are not counted.)^ Use the
   1886 ** [sqlite3_total_changes()] function to find the total number of changes
   1887 ** including changes caused by triggers and foreign key actions.
   1888 **
   1889 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
   1890 ** are not counted.  Only real table changes are counted.
   1891 **
   1892 ** ^(A "row change" is a change to a single row of a single table
   1893 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
   1894 ** are changed as side effects of [REPLACE] constraint resolution,
   1895 ** rollback, ABORT processing, [DROP TABLE], or by any other
   1896 ** mechanisms do not count as direct row changes.)^
   1897 **
   1898 ** A "trigger context" is a scope of execution that begins and
   1899 ** ends with the script of a [CREATE TRIGGER | trigger].
   1900 ** Most SQL statements are
   1901 ** evaluated outside of any trigger.  This is the "top level"
   1902 ** trigger context.  If a trigger fires from the top level, a
   1903 ** new trigger context is entered for the duration of that one
   1904 ** trigger.  Subtriggers create subcontexts for their duration.
   1905 **
   1906 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
   1907 ** not create a new trigger context.
   1908 **
   1909 ** ^This function returns the number of direct row changes in the
   1910 ** most recent INSERT, UPDATE, or DELETE statement within the same
   1911 ** trigger context.
   1912 **
   1913 ** ^Thus, when called from the top level, this function returns the
   1914 ** number of changes in the most recent INSERT, UPDATE, or DELETE
   1915 ** that also occurred at the top level.  ^(Within the body of a trigger,
   1916 ** the sqlite3_changes() interface can be called to find the number of
   1917 ** changes in the most recently completed INSERT, UPDATE, or DELETE
   1918 ** statement within the body of the same trigger.
   1919 ** However, the number returned does not include changes
   1920 ** caused by subtriggers since those have their own context.)^
   1921 **
   1922 ** See also the [sqlite3_total_changes()] interface, the
   1923 ** [count_changes pragma], and the [changes() SQL function].
   1924 **
   1925 ** If a separate thread makes changes on the same database connection
   1926 ** while [sqlite3_changes()] is running then the value returned
   1927 ** is unpredictable and not meaningful.
   1928 */
   1929 SQLITE_API int sqlite3_changes(sqlite3*);
   1930 
   1931 /*
   1932 ** CAPI3REF: Total Number Of Rows Modified
   1933 **
   1934 ** ^This function returns the number of row changes caused by [INSERT],
   1935 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
   1936 ** ^(The count returned by sqlite3_total_changes() includes all changes
   1937 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
   1938 ** [foreign key actions]. However,
   1939 ** the count does not include changes used to implement [REPLACE] constraints,
   1940 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
   1941 ** count does not include rows of views that fire an [INSTEAD OF trigger],
   1942 ** though if the INSTEAD OF trigger makes changes of its own, those changes
   1943 ** are counted.)^
   1944 ** ^The sqlite3_total_changes() function counts the changes as soon as
   1945 ** the statement that makes them is completed (when the statement handle
   1946 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
   1947 **
   1948 ** See also the [sqlite3_changes()] interface, the
   1949 ** [count_changes pragma], and the [total_changes() SQL function].
   1950 **
   1951 ** If a separate thread makes changes on the same database connection
   1952 ** while [sqlite3_total_changes()] is running then the value
   1953 ** returned is unpredictable and not meaningful.
   1954 */
   1955 SQLITE_API int sqlite3_total_changes(sqlite3*);
   1956 
   1957 /*
   1958 ** CAPI3REF: Interrupt A Long-Running Query
   1959 **
   1960 ** ^This function causes any pending database operation to abort and
   1961 ** return at its earliest opportunity. This routine is typically
   1962 ** called in response to a user action such as pressing "Cancel"
   1963 ** or Ctrl-C where the user wants a long query operation to halt
   1964 ** immediately.
   1965 **
   1966 ** ^It is safe to call this routine from a thread different from the
   1967 ** thread that is currently running the database operation.  But it
   1968 ** is not safe to call this routine with a [database connection] that
   1969 ** is closed or might close before sqlite3_interrupt() returns.
   1970 **
   1971 ** ^If an SQL operation is very nearly finished at the time when
   1972 ** sqlite3_interrupt() is called, then it might not have an opportunity
   1973 ** to be interrupted and might continue to completion.
   1974 **
   1975 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   1976 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   1977 ** that is inside an explicit transaction, then the entire transaction
   1978 ** will be rolled back automatically.
   1979 **
   1980 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   1981 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   1982 ** that are started after the sqlite3_interrupt() call and before the
   1983 ** running statements reaches zero are interrupted as if they had been
   1984 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   1985 ** that are started after the running statement count reaches zero are
   1986 ** not effected by the sqlite3_interrupt().
   1987 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   1988 ** SQL statements is a no-op and has no effect on SQL statements
   1989 ** that are started after the sqlite3_interrupt() call returns.
   1990 **
   1991 ** If the database connection closes while [sqlite3_interrupt()]
   1992 ** is running then bad things will likely happen.
   1993 */
   1994 SQLITE_API void sqlite3_interrupt(sqlite3*);
   1995 
   1996 /*
   1997 ** CAPI3REF: Determine If An SQL Statement Is Complete
   1998 **
   1999 ** These routines are useful during command-line input to determine if the
   2000 ** currently entered text seems to form a complete SQL statement or
   2001 ** if additional input is needed before sending the text into
   2002 ** SQLite for parsing.  ^These routines return 1 if the input string
   2003 ** appears to be a complete SQL statement.  ^A statement is judged to be
   2004 ** complete if it ends with a semicolon token and is not a prefix of a
   2005 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   2006 ** string literals or quoted identifier names or comments are not
   2007 ** independent tokens (they are part of the token in which they are
   2008 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   2009 ** and comments that follow the final semicolon are ignored.
   2010 **
   2011 ** ^These routines return 0 if the statement is incomplete.  ^If a
   2012 ** memory allocation fails, then SQLITE_NOMEM is returned.
   2013 **
   2014 ** ^These routines do not parse the SQL statements thus
   2015 ** will not detect syntactically incorrect SQL.
   2016 **
   2017 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   2018 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   2019 ** automatically by sqlite3_complete16().  If that initialization fails,
   2020 ** then the return value from sqlite3_complete16() will be non-zero
   2021 ** regardless of whether or not the input SQL is complete.)^
   2022 **
   2023 ** The input to [sqlite3_complete()] must be a zero-terminated
   2024 ** UTF-8 string.
   2025 **
   2026 ** The input to [sqlite3_complete16()] must be a zero-terminated
   2027 ** UTF-16 string in native byte order.
   2028 */
   2029 SQLITE_API int sqlite3_complete(const char *sql);
   2030 SQLITE_API int sqlite3_complete16(const void *sql);
   2031 
   2032 /*
   2033 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   2034 **
   2035 ** ^This routine sets a callback function that might be invoked whenever
   2036 ** an attempt is made to open a database table that another thread
   2037 ** or process has locked.
   2038 **
   2039 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
   2040 ** is returned immediately upon encountering the lock.  ^If the busy callback
   2041 ** is not NULL, then the callback might be invoked with two arguments.
   2042 **
   2043 ** ^The first argument to the busy handler is a copy of the void* pointer which
   2044 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   2045 ** the busy handler callback is the number of times that the busy handler has
   2046 ** been invoked for this locking event.  ^If the
   2047 ** busy callback returns 0, then no additional attempts are made to
   2048 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
   2049 ** ^If the callback returns non-zero, then another attempt
   2050 ** is made to open the database for reading and the cycle repeats.
   2051 **
   2052 ** The presence of a busy handler does not guarantee that it will be invoked
   2053 ** when there is lock contention. ^If SQLite determines that invoking the busy
   2054 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   2055 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
   2056 ** Consider a scenario where one process is holding a read lock that
   2057 ** it is trying to promote to a reserved lock and
   2058 ** a second process is holding a reserved lock that it is trying
   2059 ** to promote to an exclusive lock.  The first process cannot proceed
   2060 ** because it is blocked by the second and the second process cannot
   2061 ** proceed because it is blocked by the first.  If both processes
   2062 ** invoke the busy handlers, neither will make any progress.  Therefore,
   2063 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   2064 ** will induce the first process to release its read lock and allow
   2065 ** the second process to proceed.
   2066 **
   2067 ** ^The default busy callback is NULL.
   2068 **
   2069 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
   2070 ** when SQLite is in the middle of a large transaction where all the
   2071 ** changes will not fit into the in-memory cache.  SQLite will
   2072 ** already hold a RESERVED lock on the database file, but it needs
   2073 ** to promote this lock to EXCLUSIVE so that it can spill cache
   2074 ** pages into the database file without harm to concurrent
   2075 ** readers.  ^If it is unable to promote the lock, then the in-memory
   2076 ** cache will be left in an inconsistent state and so the error
   2077 ** code is promoted from the relatively benign [SQLITE_BUSY] to
   2078 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
   2079 ** forces an automatic rollback of the changes.  See the
   2080 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
   2081 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
   2082 ** this is important.
   2083 **
   2084 ** ^(There can only be a single busy handler defined for each
   2085 ** [database connection].  Setting a new busy handler clears any
   2086 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   2087 ** will also set or clear the busy handler.
   2088 **
   2089 ** The busy callback should not take any actions which modify the
   2090 ** database connection that invoked the busy handler.  Any such actions
   2091 ** result in undefined behavior.
   2092 **
   2093 ** A busy handler must not close the database connection
   2094 ** or [prepared statement] that invoked the busy handler.
   2095 */
   2096 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
   2097 
   2098 /*
   2099 ** CAPI3REF: Set A Busy Timeout
   2100 **
   2101 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   2102 ** for a specified amount of time when a table is locked.  ^The handler
   2103 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   2104 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   2105 ** the handler returns 0 which causes [sqlite3_step()] to return
   2106 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
   2107 **
   2108 ** ^Calling this routine with an argument less than or equal to zero
   2109 ** turns off all busy handlers.
   2110 **
   2111 ** ^(There can only be a single busy handler for a particular
   2112 ** [database connection] any any given moment.  If another busy handler
   2113 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   2114 ** this routine, that other busy handler is cleared.)^
   2115 */
   2116 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   2117 
   2118 /*
   2119 ** CAPI3REF: Convenience Routines For Running Queries
   2120 **
   2121 ** Definition: A <b>result table</b> is memory data structure created by the
   2122 ** [sqlite3_get_table()] interface.  A result table records the
   2123 ** complete query results from one or more queries.
   2124 **
   2125 ** The table conceptually has a number of rows and columns.  But
   2126 ** these numbers are not part of the result table itself.  These
   2127 ** numbers are obtained separately.  Let N be the number of rows
   2128 ** and M be the number of columns.
   2129 **
   2130 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   2131 ** There are (N+1)*M elements in the array.  The first M pointers point
   2132 ** to zero-terminated strings that  contain the names of the columns.
   2133 ** The remaining entries all point to query results.  NULL values result
   2134 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   2135 ** string representation as returned by [sqlite3_column_text()].
   2136 **
   2137 ** A result table might consist of one or more memory allocations.
   2138 ** It is not safe to pass a result table directly to [sqlite3_free()].
   2139 ** A result table should be deallocated using [sqlite3_free_table()].
   2140 **
   2141 ** As an example of the result table format, suppose a query result
   2142 ** is as follows:
   2143 **
   2144 ** <blockquote><pre>
   2145 **        Name        | Age
   2146 **        -----------------------
   2147 **        Alice       | 43
   2148 **        Bob         | 28
   2149 **        Cindy       | 21
   2150 ** </pre></blockquote>
   2151 **
   2152 ** There are two column (M==2) and three rows (N==3).  Thus the
   2153 ** result table has 8 entries.  Suppose the result table is stored
   2154 ** in an array names azResult.  Then azResult holds this content:
   2155 **
   2156 ** <blockquote><pre>
   2157 **        azResult&#91;0] = "Name";
   2158 **        azResult&#91;1] = "Age";
   2159 **        azResult&#91;2] = "Alice";
   2160 **        azResult&#91;3] = "43";
   2161 **        azResult&#91;4] = "Bob";
   2162 **        azResult&#91;5] = "28";
   2163 **        azResult&#91;6] = "Cindy";
   2164 **        azResult&#91;7] = "21";
   2165 ** </pre></blockquote>
   2166 **
   2167 ** ^The sqlite3_get_table() function evaluates one or more
   2168 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   2169 ** string of its 2nd parameter and returns a result table to the
   2170 ** pointer given in its 3rd parameter.
   2171 **
   2172 ** After the application has finished with the result from sqlite3_get_table(),
   2173 ** it should pass the result table pointer to sqlite3_free_table() in order to
   2174 ** release the memory that was malloced.  Because of the way the
   2175 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   2176 ** function must not try to call [sqlite3_free()] directly.  Only
   2177 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   2178 **
   2179 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
   2180 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   2181 ** to any internal data structures of SQLite.  It uses only the public
   2182 ** interface defined here.  As a consequence, errors that occur in the
   2183 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   2184 ** reflected in subsequent calls to [sqlite3_errcode()] or
   2185 ** [sqlite3_errmsg()].)^
   2186 */
   2187 SQLITE_API int sqlite3_get_table(
   2188   sqlite3 *db,          /* An open database */
   2189   const char *zSql,     /* SQL to be evaluated */
   2190   char ***pazResult,    /* Results of the query */
   2191   int *pnRow,           /* Number of result rows written here */
   2192   int *pnColumn,        /* Number of result columns written here */
   2193   char **pzErrmsg       /* Error msg written here */
   2194 );
   2195 SQLITE_API void sqlite3_free_table(char **result);
   2196 
   2197 /*
   2198 ** CAPI3REF: Formatted String Printing Functions
   2199 **
   2200 ** These routines are work-alikes of the "printf()" family of functions
   2201 ** from the standard C library.
   2202 **
   2203 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   2204 ** results into memory obtained from [sqlite3_malloc()].
   2205 ** The strings returned by these two routines should be
   2206 ** released by [sqlite3_free()].  ^Both routines return a
   2207 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   2208 ** memory to hold the resulting string.
   2209 **
   2210 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
   2211 ** the standard C library.  The result is written into the
   2212 ** buffer supplied as the second parameter whose size is given by
   2213 ** the first parameter. Note that the order of the
   2214 ** first two parameters is reversed from snprintf().)^  This is an
   2215 ** historical accident that cannot be fixed without breaking
   2216 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   2217 ** returns a pointer to its buffer instead of the number of
   2218 ** characters actually written into the buffer.)^  We admit that
   2219 ** the number of characters written would be a more useful return
   2220 ** value but we cannot change the implementation of sqlite3_snprintf()
   2221 ** now without breaking compatibility.
   2222 **
   2223 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   2224 ** guarantees that the buffer is always zero-terminated.  ^The first
   2225 ** parameter "n" is the total size of the buffer, including space for
   2226 ** the zero terminator.  So the longest string that can be completely
   2227 ** written will be n-1 characters.
   2228 **
   2229 ** These routines all implement some additional formatting
   2230 ** options that are useful for constructing SQL statements.
   2231 ** All of the usual printf() formatting options apply.  In addition, there
   2232 ** is are "%q", "%Q", and "%z" options.
   2233 **
   2234 ** ^(The %q option works like %s in that it substitutes a null-terminated
   2235 ** string from the argument list.  But %q also doubles every '\'' character.
   2236 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   2237 ** character it escapes that character and allows it to be inserted into
   2238 ** the string.
   2239 **
   2240 ** For example, assume the string variable zText contains text as follows:
   2241 **
   2242 ** <blockquote><pre>
   2243 **  char *zText = "It's a happy day!";
   2244 ** </pre></blockquote>
   2245 **
   2246 ** One can use this text in an SQL statement as follows:
   2247 **
   2248 ** <blockquote><pre>
   2249 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   2250 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2251 **  sqlite3_free(zSQL);
   2252 ** </pre></blockquote>
   2253 **
   2254 ** Because the %q format string is used, the '\'' character in zText
   2255 ** is escaped and the SQL generated is as follows:
   2256 **
   2257 ** <blockquote><pre>
   2258 **  INSERT INTO table1 VALUES('It''s a happy day!')
   2259 ** </pre></blockquote>
   2260 **
   2261 ** This is correct.  Had we used %s instead of %q, the generated SQL
   2262 ** would have looked like this:
   2263 **
   2264 ** <blockquote><pre>
   2265 **  INSERT INTO table1 VALUES('It's a happy day!');
   2266 ** </pre></blockquote>
   2267 **
   2268 ** This second example is an SQL syntax error.  As a general rule you should
   2269 ** always use %q instead of %s when inserting text into a string literal.
   2270 **
   2271 ** ^(The %Q option works like %q except it also adds single quotes around
   2272 ** the outside of the total string.  Additionally, if the parameter in the
   2273 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   2274 ** single quotes).)^  So, for example, one could say:
   2275 **
   2276 ** <blockquote><pre>
   2277 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   2278 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2279 **  sqlite3_free(zSQL);
   2280 ** </pre></blockquote>
   2281 **
   2282 ** The code above will render a correct SQL statement in the zSQL
   2283 ** variable even if the zText variable is a NULL pointer.
   2284 **
   2285 ** ^(The "%z" formatting option works like "%s" but with the
   2286 ** addition that after the string has been read and copied into
   2287 ** the result, [sqlite3_free()] is called on the input string.)^
   2288 */
   2289 SQLITE_API char *sqlite3_mprintf(const char*,...);
   2290 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   2291 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   2292 
   2293 /*
   2294 ** CAPI3REF: Memory Allocation Subsystem
   2295 **
   2296 ** The SQLite core uses these three routines for all of its own
   2297 ** internal memory allocation needs. "Core" in the previous sentence
   2298 ** does not include operating-system specific VFS implementation.  The
   2299 ** Windows VFS uses native malloc() and free() for some operations.
   2300 **
   2301 ** ^The sqlite3_malloc() routine returns a pointer to a block
   2302 ** of memory at least N bytes in length, where N is the parameter.
   2303 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   2304 ** memory, it returns a NULL pointer.  ^If the parameter N to
   2305 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   2306 ** a NULL pointer.
   2307 **
   2308 ** ^Calling sqlite3_free() with a pointer previously returned
   2309 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   2310 ** that it might be reused.  ^The sqlite3_free() routine is
   2311 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   2312 ** to sqlite3_free() is harmless.  After being freed, memory
   2313 ** should neither be read nor written.  Even reading previously freed
   2314 ** memory might result in a segmentation fault or other severe error.
   2315 ** Memory corruption, a segmentation fault, or other severe error
   2316 ** might result if sqlite3_free() is called with a non-NULL pointer that
   2317 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   2318 **
   2319 ** ^(The sqlite3_realloc() interface attempts to resize a
   2320 ** prior memory allocation to be at least N bytes, where N is the
   2321 ** second parameter.  The memory allocation to be resized is the first
   2322 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
   2323 ** is a NULL pointer then its behavior is identical to calling
   2324 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
   2325 ** ^If the second parameter to sqlite3_realloc() is zero or
   2326 ** negative then the behavior is exactly the same as calling
   2327 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
   2328 ** ^sqlite3_realloc() returns a pointer to a memory allocation
   2329 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
   2330 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   2331 ** of the prior allocation are copied into the beginning of buffer returned
   2332 ** by sqlite3_realloc() and the prior allocation is freed.
   2333 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
   2334 ** is not freed.
   2335 **
   2336 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
   2337 ** is always aligned to at least an 8 byte boundary.
   2338 **
   2339 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   2340 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   2341 ** implementation of these routines to be omitted.  That capability
   2342 ** is no longer provided.  Only built-in memory allocators can be used.
   2343 **
   2344 ** The Windows OS interface layer calls
   2345 ** the system malloc() and free() directly when converting
   2346 ** filenames between the UTF-8 encoding used by SQLite
   2347 ** and whatever filename encoding is used by the particular Windows
   2348 ** installation.  Memory allocation errors are detected, but
   2349 ** they are reported back as [SQLITE_CANTOPEN] or
   2350 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   2351 **
   2352 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   2353 ** must be either NULL or else pointers obtained from a prior
   2354 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   2355 ** not yet been released.
   2356 **
   2357 ** The application must not read or write any part of
   2358 ** a block of memory after it has been released using
   2359 ** [sqlite3_free()] or [sqlite3_realloc()].
   2360 */
   2361 SQLITE_API void *sqlite3_malloc(int);
   2362 SQLITE_API void *sqlite3_realloc(void*, int);
   2363 SQLITE_API void sqlite3_free(void*);
   2364 
   2365 /*
   2366 ** CAPI3REF: Memory Allocator Statistics
   2367 **
   2368 ** SQLite provides these two interfaces for reporting on the status
   2369 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   2370 ** routines, which form the built-in memory allocation subsystem.
   2371 **
   2372 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   2373 ** of memory currently outstanding (malloced but not freed).
   2374 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   2375 ** value of [sqlite3_memory_used()] since the high-water mark
   2376 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   2377 ** [sqlite3_memory_highwater()] include any overhead
   2378 ** added by SQLite in its implementation of [sqlite3_malloc()],
   2379 ** but not overhead added by the any underlying system library
   2380 ** routines that [sqlite3_malloc()] may call.
   2381 **
   2382 ** ^The memory high-water mark is reset to the current value of
   2383 ** [sqlite3_memory_used()] if and only if the parameter to
   2384 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   2385 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   2386 ** prior to the reset.
   2387 */
   2388 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   2389 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   2390 
   2391 /*
   2392 ** CAPI3REF: Pseudo-Random Number Generator
   2393 **
   2394 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   2395 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   2396 ** already uses the largest possible [ROWID].  The PRNG is also used for
   2397 ** the build-in random() and randomblob() SQL functions.  This interface allows
   2398 ** applications to access the same PRNG for other purposes.
   2399 **
   2400 ** ^A call to this routine stores N bytes of randomness into buffer P.
   2401 **
   2402 ** ^The first time this routine is invoked (either internally or by
   2403 ** the application) the PRNG is seeded using randomness obtained
   2404 ** from the xRandomness method of the default [sqlite3_vfs] object.
   2405 ** ^On all subsequent invocations, the pseudo-randomness is generated
   2406 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   2407 ** method.
   2408 */
   2409 SQLITE_API void sqlite3_randomness(int N, void *P);
   2410 
   2411 /*
   2412 ** CAPI3REF: Compile-Time Authorization Callbacks
   2413 **
   2414 ** ^This routine registers a authorizer callback with a particular
   2415 ** [database connection], supplied in the first argument.
   2416 ** ^The authorizer callback is invoked as SQL statements are being compiled
   2417 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   2418 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
   2419 ** points during the compilation process, as logic is being created
   2420 ** to perform various actions, the authorizer callback is invoked to
   2421 ** see if those actions are allowed.  ^The authorizer callback should
   2422 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   2423 ** specific action but allow the SQL statement to continue to be
   2424 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   2425 ** rejected with an error.  ^If the authorizer callback returns
   2426 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   2427 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   2428 ** the authorizer will fail with an error message.
   2429 **
   2430 ** When the callback returns [SQLITE_OK], that means the operation
   2431 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   2432 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   2433 ** authorizer will fail with an error message explaining that
   2434 ** access is denied.
   2435 **
   2436 ** ^The first parameter to the authorizer callback is a copy of the third
   2437 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   2438 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   2439 ** the particular action to be authorized. ^The third through sixth parameters
   2440 ** to the callback are zero-terminated strings that contain additional
   2441 ** details about the action to be authorized.
   2442 **
   2443 ** ^If the action code is [SQLITE_READ]
   2444 ** and the callback returns [SQLITE_IGNORE] then the
   2445 ** [prepared statement] statement is constructed to substitute
   2446 ** a NULL value in place of the table column that would have
   2447 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   2448 ** return can be used to deny an untrusted user access to individual
   2449 ** columns of a table.
   2450 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   2451 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   2452 ** [truncate optimization] is disabled and all rows are deleted individually.
   2453 **
   2454 ** An authorizer is used when [sqlite3_prepare | preparing]
   2455 ** SQL statements from an untrusted source, to ensure that the SQL statements
   2456 ** do not try to access data they are not allowed to see, or that they do not
   2457 ** try to execute malicious statements that damage the database.  For
   2458 ** example, an application may allow a user to enter arbitrary
   2459 ** SQL queries for evaluation by a database.  But the application does
   2460 ** not want the user to be able to make arbitrary changes to the
   2461 ** database.  An authorizer could then be put in place while the
   2462 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   2463 ** disallows everything except [SELECT] statements.
   2464 **
   2465 ** Applications that need to process SQL from untrusted sources
   2466 ** might also consider lowering resource limits using [sqlite3_limit()]
   2467 ** and limiting database size using the [max_page_count] [PRAGMA]
   2468 ** in addition to using an authorizer.
   2469 **
   2470 ** ^(Only a single authorizer can be in place on a database connection
   2471 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   2472 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   2473 ** The authorizer is disabled by default.
   2474 **
   2475 ** The authorizer callback must not do anything that will modify
   2476 ** the database connection that invoked the authorizer callback.
   2477 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2478 ** database connections for the meaning of "modify" in this paragraph.
   2479 **
   2480 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   2481 ** statement might be re-prepared during [sqlite3_step()] due to a
   2482 ** schema change.  Hence, the application should ensure that the
   2483 ** correct authorizer callback remains in place during the [sqlite3_step()].
   2484 **
   2485 ** ^Note that the authorizer callback is invoked only during
   2486 ** [sqlite3_prepare()] or its variants.  Authorization is not
   2487 ** performed during statement evaluation in [sqlite3_step()], unless
   2488 ** as stated in the previous paragraph, sqlite3_step() invokes
   2489 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   2490 */
   2491 SQLITE_API int sqlite3_set_authorizer(
   2492   sqlite3*,
   2493   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   2494   void *pUserData
   2495 );
   2496 
   2497 /*
   2498 ** CAPI3REF: Authorizer Return Codes
   2499 **
   2500 ** The [sqlite3_set_authorizer | authorizer callback function] must
   2501 ** return either [SQLITE_OK] or one of these two constants in order
   2502 ** to signal SQLite whether or not the action is permitted.  See the
   2503 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   2504 ** information.
   2505 */
   2506 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   2507 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   2508 
   2509 /*
   2510 ** CAPI3REF: Authorizer Action Codes
   2511 **
   2512 ** The [sqlite3_set_authorizer()] interface registers a callback function
   2513 ** that is invoked to authorize certain SQL statement actions.  The
   2514 ** second parameter to the callback is an integer code that specifies
   2515 ** what action is being authorized.  These are the integer action codes that
   2516 ** the authorizer callback may be passed.
   2517 **
   2518 ** These action code values signify what kind of operation is to be
   2519 ** authorized.  The 3rd and 4th parameters to the authorization
   2520 ** callback function will be parameters or NULL depending on which of these
   2521 ** codes is used as the second parameter.  ^(The 5th parameter to the
   2522 ** authorizer callback is the name of the database ("main", "temp",
   2523 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   2524 ** is the name of the inner-most trigger or view that is responsible for
   2525 ** the access attempt or NULL if this access attempt is directly from
   2526 ** top-level SQL code.
   2527 */
   2528 /******************************************* 3rd ************ 4th ***********/
   2529 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   2530 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   2531 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   2532 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   2533 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   2534 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   2535 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   2536 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   2537 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   2538 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   2539 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   2540 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   2541 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   2542 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   2543 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   2544 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   2545 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   2546 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   2547 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   2548 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   2549 #define SQLITE_SELECT               21   /* NULL            NULL            */
   2550 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   2551 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   2552 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   2553 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   2554 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   2555 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   2556 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   2557 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   2558 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   2559 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   2560 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   2561 #define SQLITE_COPY                  0   /* No longer used */
   2562 
   2563 /*
   2564 ** CAPI3REF: Tracing And Profiling Functions
   2565 ** EXPERIMENTAL
   2566 **
   2567 ** These routines register callback functions that can be used for
   2568 ** tracing and profiling the execution of SQL statements.
   2569 **
   2570 ** ^The callback function registered by sqlite3_trace() is invoked at
   2571 ** various times when an SQL statement is being run by [sqlite3_step()].
   2572 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   2573 ** SQL statement text as the statement first begins executing.
   2574 ** ^(Additional sqlite3_trace() callbacks might occur
   2575 ** as each triggered subprogram is entered.  The callbacks for triggers
   2576 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   2577 **
   2578 ** ^The callback function registered by sqlite3_profile() is invoked
   2579 ** as each SQL statement finishes.  ^The profile callback contains
   2580 ** the original statement text and an estimate of wall-clock time
   2581 ** of how long that statement took to run.
   2582 */
   2583 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
   2584 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   2585    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   2586 
   2587 /*
   2588 ** CAPI3REF: Query Progress Callbacks
   2589 **
   2590 ** ^This routine configures a callback function - the
   2591 ** progress callback - that is invoked periodically during long
   2592 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
   2593 ** [sqlite3_get_table()].  An example use for this
   2594 ** interface is to keep a GUI updated during a large query.
   2595 **
   2596 ** ^If the progress callback returns non-zero, the operation is
   2597 ** interrupted.  This feature can be used to implement a
   2598 ** "Cancel" button on a GUI progress dialog box.
   2599 **
   2600 ** The progress handler must not do anything that will modify
   2601 ** the database connection that invoked the progress handler.
   2602 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2603 ** database connections for the meaning of "modify" in this paragraph.
   2604 **
   2605 */
   2606 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   2607 
   2608 /*
   2609 ** CAPI3REF: Opening A New Database Connection
   2610 **
   2611 ** ^These routines open an SQLite database file whose name is given by the
   2612 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   2613 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   2614 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   2615 ** returned in *ppDb, even if an error occurs.  The only exception is that
   2616 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   2617 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   2618 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   2619 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   2620 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   2621 ** an English language description of the error following a failure of any
   2622 ** of the sqlite3_open() routines.
   2623 **
   2624 ** ^The default encoding for the database will be UTF-8 if
   2625 ** sqlite3_open() or sqlite3_open_v2() is called and
   2626 ** UTF-16 in the native byte order if sqlite3_open16() is used.
   2627 **
   2628 ** Whether or not an error occurs when it is opened, resources
   2629 ** associated with the [database connection] handle should be released by
   2630 ** passing it to [sqlite3_close()] when it is no longer required.
   2631 **
   2632 ** The sqlite3_open_v2() interface works like sqlite3_open()
   2633 ** except that it accepts two additional parameters for additional control
   2634 ** over the new database connection.  ^(The flags parameter to
   2635 ** sqlite3_open_v2() can take one of
   2636 ** the following three values, optionally combined with the
   2637 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   2638 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
   2639 **
   2640 ** <dl>
   2641 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   2642 ** <dd>The database is opened in read-only mode.  If the database does not
   2643 ** already exist, an error is returned.</dd>)^
   2644 **
   2645 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   2646 ** <dd>The database is opened for reading and writing if possible, or reading
   2647 ** only if the file is write protected by the operating system.  In either
   2648 ** case the database must already exist, otherwise an error is returned.</dd>)^
   2649 **
   2650 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   2651 ** <dd>The database is opened for reading and writing, and is creates it if
   2652 ** it does not already exist. This is the behavior that is always used for
   2653 ** sqlite3_open() and sqlite3_open16().</dd>)^
   2654 ** </dl>
   2655 **
   2656 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   2657 ** combinations shown above or one of the combinations shown above combined
   2658 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
   2659 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
   2660 ** then the behavior is undefined.
   2661 **
   2662 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   2663 ** opens in the multi-thread [threading mode] as long as the single-thread
   2664 ** mode has not been set at compile-time or start-time.  ^If the
   2665 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   2666 ** in the serialized [threading mode] unless single-thread was
   2667 ** previously selected at compile-time or start-time.
   2668 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   2669 ** eligible to use [shared cache mode], regardless of whether or not shared
   2670 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   2671 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   2672 ** participate in [shared cache mode] even if it is enabled.
   2673 **
   2674 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   2675 ** is created for the connection.  ^This in-memory database will vanish when
   2676 ** the database connection is closed.  Future versions of SQLite might
   2677 ** make use of additional special filenames that begin with the ":" character.
   2678 ** It is recommended that when a database filename actually does begin with
   2679 ** a ":" character you should prefix the filename with a pathname such as
   2680 ** "./" to avoid ambiguity.
   2681 **
   2682 ** ^If the filename is an empty string, then a private, temporary
   2683 ** on-disk database will be created.  ^This private database will be
   2684 ** automatically deleted as soon as the database connection is closed.
   2685 **
   2686 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   2687 ** [sqlite3_vfs] object that defines the operating system interface that
   2688 ** the new database connection should use.  ^If the fourth parameter is
   2689 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   2690 **
   2691 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   2692 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   2693 ** codepage is currently defined.  Filenames containing international
   2694 ** characters must be converted to UTF-8 prior to passing them into
   2695 ** sqlite3_open() or sqlite3_open_v2().
   2696 */
   2697 SQLITE_API int sqlite3_open(
   2698   const char *filename,   /* Database filename (UTF-8) */
   2699   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2700 );
   2701 SQLITE_API int sqlite3_open16(
   2702   const void *filename,   /* Database filename (UTF-16) */
   2703   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2704 );
   2705 SQLITE_API int sqlite3_open_v2(
   2706   const char *filename,   /* Database filename (UTF-8) */
   2707   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   2708   int flags,              /* Flags */
   2709   const char *zVfs        /* Name of VFS module to use */
   2710 );
   2711 
   2712 /*
   2713 ** CAPI3REF: Error Codes And Messages
   2714 **
   2715 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
   2716 ** [extended result code] for the most recent failed sqlite3_* API call
   2717 ** associated with a [database connection]. If a prior API call failed
   2718 ** but the most recent API call succeeded, the return value from
   2719 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
   2720 ** interface is the same except that it always returns the
   2721 ** [extended result code] even when extended result codes are
   2722 ** disabled.
   2723 **
   2724 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   2725 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   2726 ** ^(Memory to hold the error message string is managed internally.
   2727 ** The application does not need to worry about freeing the result.
   2728 ** However, the error string might be overwritten or deallocated by
   2729 ** subsequent calls to other SQLite interface functions.)^
   2730 **
   2731 ** When the serialized [threading mode] is in use, it might be the
   2732 ** case that a second error occurs on a separate thread in between
   2733 ** the time of the first error and the call to these interfaces.
   2734 ** When that happens, the second error will be reported since these
   2735 ** interfaces always report the most recent result.  To avoid
   2736 ** this, each thread can obtain exclusive use of the [database connection] D
   2737 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   2738 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   2739 ** all calls to the interfaces listed here are completed.
   2740 **
   2741 ** If an interface fails with SQLITE_MISUSE, that means the interface
   2742 ** was invoked incorrectly by the application.  In that case, the
   2743 ** error code and message may or may not be set.
   2744 */
   2745 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   2746 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   2747 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   2748 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   2749 
   2750 /*
   2751 ** CAPI3REF: SQL Statement Object
   2752 ** KEYWORDS: {prepared statement} {prepared statements}
   2753 **
   2754 ** An instance of this object represents a single SQL statement.
   2755 ** This object is variously known as a "prepared statement" or a
   2756 ** "compiled SQL statement" or simply as a "statement".
   2757 **
   2758 ** The life of a statement object goes something like this:
   2759 **
   2760 ** <ol>
   2761 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
   2762 **      function.
   2763 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
   2764 **      interfaces.
   2765 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   2766 ** <li> Reset the statement using [sqlite3_reset()] then go back
   2767 **      to step 2.  Do this zero or more times.
   2768 ** <li> Destroy the object using [sqlite3_finalize()].
   2769 ** </ol>
   2770 **
   2771 ** Refer to documentation on individual methods above for additional
   2772 ** information.
   2773 */
   2774 typedef struct sqlite3_stmt sqlite3_stmt;
   2775 
   2776 /*
   2777 ** CAPI3REF: Run-time Limits
   2778 **
   2779 ** ^(This interface allows the size of various constructs to be limited
   2780 ** on a connection by connection basis.  The first parameter is the
   2781 ** [database connection] whose limit is to be set or queried.  The
   2782 ** second parameter is one of the [limit categories] that define a
   2783 ** class of constructs to be size limited.  The third parameter is the
   2784 ** new limit for that construct.  The function returns the old limit.)^
   2785 **
   2786 ** ^If the new limit is a negative number, the limit is unchanged.
   2787 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
   2788 ** [limits | hard upper bound]
   2789 ** set by a compile-time C preprocessor macro named
   2790 ** [limits | SQLITE_MAX_XYZ].
   2791 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   2792 ** ^Attempts to increase a limit above its hard upper bound are
   2793 ** silently truncated to the hard upper bound.
   2794 **
   2795 ** Run-time limits are intended for use in applications that manage
   2796 ** both their own internal database and also databases that are controlled
   2797 ** by untrusted external sources.  An example application might be a
   2798 ** web browser that has its own databases for storing history and
   2799 ** separate databases controlled by JavaScript applications downloaded
   2800 ** off the Internet.  The internal databases can be given the
   2801 ** large, default limits.  Databases managed by external sources can
   2802 ** be given much smaller limits designed to prevent a denial of service
   2803 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   2804 ** interface to further control untrusted SQL.  The size of the database
   2805 ** created by an untrusted script can be contained using the
   2806 ** [max_page_count] [PRAGMA].
   2807 **
   2808 ** New run-time limit categories may be added in future releases.
   2809 */
   2810 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   2811 
   2812 /*
   2813 ** CAPI3REF: Run-Time Limit Categories
   2814 ** KEYWORDS: {limit category} {*limit categories}
   2815 **
   2816 ** These constants define various performance limits
   2817 ** that can be lowered at run-time using [sqlite3_limit()].
   2818 ** The synopsis of the meanings of the various limits is shown below.
   2819 ** Additional information is available at [limits | Limits in SQLite].
   2820 **
   2821 ** <dl>
   2822 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   2823 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
   2824 **
   2825 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   2826 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   2827 **
   2828 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   2829 ** <dd>The maximum number of columns in a table definition or in the
   2830 ** result set of a [SELECT] or the maximum number of columns in an index
   2831 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   2832 **
   2833 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   2834 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   2835 **
   2836 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   2837 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   2838 **
   2839 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   2840 ** <dd>The maximum number of instructions in a virtual machine program
   2841 ** used to implement an SQL statement.</dd>)^
   2842 **
   2843 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   2844 ** <dd>The maximum number of arguments on a function.</dd>)^
   2845 **
   2846 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   2847 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   2848 **
   2849 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   2850 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   2851 ** [GLOB] operators.</dd>)^
   2852 **
   2853 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   2854 ** <dd>The maximum number of variables in an SQL statement that can
   2855 ** be bound.</dd>)^
   2856 **
   2857 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   2858 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   2859 ** </dl>
   2860 */
   2861 #define SQLITE_LIMIT_LENGTH                    0
   2862 #define SQLITE_LIMIT_SQL_LENGTH                1
   2863 #define SQLITE_LIMIT_COLUMN                    2
   2864 #define SQLITE_LIMIT_EXPR_DEPTH                3
   2865 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   2866 #define SQLITE_LIMIT_VDBE_OP                   5
   2867 #define SQLITE_LIMIT_FUNCTION_ARG              6
   2868 #define SQLITE_LIMIT_ATTACHED                  7
   2869 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   2870 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   2871 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   2872 
   2873 /*
   2874 ** CAPI3REF: Compiling An SQL Statement
   2875 ** KEYWORDS: {SQL statement compiler}
   2876 **
   2877 ** To execute an SQL query, it must first be compiled into a byte-code
   2878 ** program using one of these routines.
   2879 **
   2880 ** The first argument, "db", is a [database connection] obtained from a
   2881 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   2882 ** [sqlite3_open16()].  The database connection must not have been closed.
   2883 **
   2884 ** The second argument, "zSql", is the statement to be compiled, encoded
   2885 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
   2886 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
   2887 ** use UTF-16.
   2888 **
   2889 ** ^If the nByte argument is less than zero, then zSql is read up to the
   2890 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
   2891 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
   2892 ** zSql string ends at either the first '\000' or '\u0000' character or
   2893 ** the nByte-th byte, whichever comes first. If the caller knows
   2894 ** that the supplied string is nul-terminated, then there is a small
   2895 ** performance advantage to be gained by passing an nByte parameter that
   2896 ** is equal to the number of bytes in the input string <i>including</i>
   2897 ** the nul-terminator bytes.
   2898 **
   2899 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   2900 ** past the end of the first SQL statement in zSql.  These routines only
   2901 ** compile the first statement in zSql, so *pzTail is left pointing to
   2902 ** what remains uncompiled.
   2903 **
   2904 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   2905 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   2906 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   2907 ** string or a comment) then *ppStmt is set to NULL.
   2908 ** The calling procedure is responsible for deleting the compiled
   2909 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   2910 ** ppStmt may not be NULL.
   2911 **
   2912 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   2913 ** otherwise an [error code] is returned.
   2914 **
   2915 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
   2916 ** recommended for all new programs. The two older interfaces are retained
   2917 ** for backwards compatibility, but their use is discouraged.
   2918 ** ^In the "v2" interfaces, the prepared statement
   2919 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   2920 ** original SQL text. This causes the [sqlite3_step()] interface to
   2921 ** behave differently in three ways:
   2922 **
   2923 ** <ol>
   2924 ** <li>
   2925 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   2926 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   2927 ** statement and try to run it again.  ^If the schema has changed in
   2928 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
   2929 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
   2930 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
   2931 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
   2932 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
   2933 ** </li>
   2934 **
   2935 ** <li>
   2936 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   2937 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   2938 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   2939 ** and the application would have to make a second call to [sqlite3_reset()]
   2940 ** in order to find the underlying cause of the problem. With the "v2" prepare
   2941 ** interfaces, the underlying reason for the error is returned immediately.
   2942 ** </li>
   2943 **
   2944 ** <li>
   2945 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
   2946 ** change the query plan for a statement, then the statement may be
   2947 ** automatically recompiled (as if there had been a schema change) on the first
   2948 ** [sqlite3_step()] call following any change to the
   2949 ** [sqlite3_bind_text | bindings] of the [parameter].
   2950 ** </li>
   2951 ** </ol>
   2952 */
   2953 SQLITE_API int sqlite3_prepare(
   2954   sqlite3 *db,            /* Database handle */
   2955   const char *zSql,       /* SQL statement, UTF-8 encoded */
   2956   int nByte,              /* Maximum length of zSql in bytes. */
   2957   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2958   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   2959 );
   2960 SQLITE_API int sqlite3_prepare_v2(
   2961   sqlite3 *db,            /* Database handle */
   2962   const char *zSql,       /* SQL statement, UTF-8 encoded */
   2963   int nByte,              /* Maximum length of zSql in bytes. */
   2964   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2965   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   2966 );
   2967 SQLITE_API int sqlite3_prepare16(
   2968   sqlite3 *db,            /* Database handle */
   2969   const void *zSql,       /* SQL statement, UTF-16 encoded */
   2970   int nByte,              /* Maximum length of zSql in bytes. */
   2971   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2972   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   2973 );
   2974 SQLITE_API int sqlite3_prepare16_v2(
   2975   sqlite3 *db,            /* Database handle */
   2976   const void *zSql,       /* SQL statement, UTF-16 encoded */
   2977   int nByte,              /* Maximum length of zSql in bytes. */
   2978   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2979   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   2980 );
   2981 
   2982 /*
   2983 ** CAPI3REF: Retrieving Statement SQL
   2984 **
   2985 ** ^This interface can be used to retrieve a saved copy of the original
   2986 ** SQL text used to create a [prepared statement] if that statement was
   2987 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
   2988 */
   2989 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   2990 
   2991 /*
   2992 ** CAPI3REF: Dynamically Typed Value Object
   2993 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   2994 **
   2995 ** SQLite uses the sqlite3_value object to represent all values
   2996 ** that can be stored in a database table. SQLite uses dynamic typing
   2997 ** for the values it stores.  ^Values stored in sqlite3_value objects
   2998 ** can be integers, floating point values, strings, BLOBs, or NULL.
   2999 **
   3000 ** An sqlite3_value object may be either "protected" or "unprotected".
   3001 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   3002 ** will accept either a protected or an unprotected sqlite3_value.
   3003 ** Every interface that accepts sqlite3_value arguments specifies
   3004 ** whether or not it requires a protected sqlite3_value.
   3005 **
   3006 ** The terms "protected" and "unprotected" refer to whether or not
   3007 ** a mutex is held.  A internal mutex is held for a protected
   3008 ** sqlite3_value object but no mutex is held for an unprotected
   3009 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   3010 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   3011 ** or if SQLite is run in one of reduced mutex modes
   3012 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   3013 ** then there is no distinction between protected and unprotected
   3014 ** sqlite3_value objects and they can be used interchangeably.  However,
   3015 ** for maximum code portability it is recommended that applications
   3016 ** still make the distinction between between protected and unprotected
   3017 ** sqlite3_value objects even when not strictly required.
   3018 **
   3019 ** ^The sqlite3_value objects that are passed as parameters into the
   3020 ** implementation of [application-defined SQL functions] are protected.
   3021 ** ^The sqlite3_value object returned by
   3022 ** [sqlite3_column_value()] is unprotected.
   3023 ** Unprotected sqlite3_value objects may only be used with
   3024 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
   3025 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   3026 ** interfaces require protected sqlite3_value objects.
   3027 */
   3028 typedef struct Mem sqlite3_value;
   3029 
   3030 /*
   3031 ** CAPI3REF: SQL Function Context Object
   3032 **
   3033 ** The context in which an SQL function executes is stored in an
   3034 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   3035 ** is always first parameter to [application-defined SQL functions].
   3036 ** The application-defined SQL function implementation will pass this
   3037 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   3038 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   3039 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   3040 ** and/or [sqlite3_set_auxdata()].
   3041 */
   3042 typedef struct sqlite3_context sqlite3_context;
   3043 
   3044 /*
   3045 ** CAPI3REF: Binding Values To Prepared Statements
   3046 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   3047 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   3048 **
   3049 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   3050 ** literals may be replaced by a [parameter] that matches one of following
   3051 ** templates:
   3052 **
   3053 ** <ul>
   3054 ** <li>  ?
   3055 ** <li>  ?NNN
   3056 ** <li>  :VVV
   3057 ** <li>  @VVV
   3058 ** <li>  $VVV
   3059 ** </ul>
   3060 **
   3061 ** In the templates above, NNN represents an integer literal,
   3062 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
   3063 ** parameters (also called "host parameter names" or "SQL parameters")
   3064 ** can be set using the sqlite3_bind_*() routines defined here.
   3065 **
   3066 ** ^The first argument to the sqlite3_bind_*() routines is always
   3067 ** a pointer to the [sqlite3_stmt] object returned from
   3068 ** [sqlite3_prepare_v2()] or its variants.
   3069 **
   3070 ** ^The second argument is the index of the SQL parameter to be set.
   3071 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   3072 ** SQL parameter is used more than once, second and subsequent
   3073 ** occurrences have the same index as the first occurrence.
   3074 ** ^The index for named parameters can be looked up using the
   3075 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   3076 ** for "?NNN" parameters is the value of NNN.
   3077 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   3078 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   3079 **
   3080 ** ^The third argument is the value to bind to the parameter.
   3081 **
   3082 ** ^(In those routines that have a fourth argument, its value is the
   3083 ** number of bytes in the parameter.  To be clear: the value is the
   3084 ** number of <u>bytes</u> in the value, not the number of characters.)^
   3085 ** ^If the fourth parameter is negative, the length of the string is
   3086 ** the number of bytes up to the first zero terminator.
   3087 **
   3088 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
   3089 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
   3090 ** string after SQLite has finished with it. ^If the fifth argument is
   3091 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   3092 ** information is in static, unmanaged space and does not need to be freed.
   3093 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   3094 ** SQLite makes its own private copy of the data immediately, before
   3095 ** the sqlite3_bind_*() routine returns.
   3096 **
   3097 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   3098 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   3099 ** (just an integer to hold its size) while it is being processed.
   3100 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   3101 ** content is later written using
   3102 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   3103 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   3104 **
   3105 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   3106 ** for the [prepared statement] or with a prepared statement for which
   3107 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   3108 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   3109 ** routine is passed a [prepared statement] that has been finalized, the
   3110 ** result is undefined and probably harmful.
   3111 **
   3112 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   3113 ** ^Unbound parameters are interpreted as NULL.
   3114 **
   3115 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   3116 ** [error code] if anything goes wrong.
   3117 ** ^[SQLITE_RANGE] is returned if the parameter
   3118 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   3119 **
   3120 ** See also: [sqlite3_bind_parameter_count()],
   3121 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   3122 */
   3123 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   3124 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   3125 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   3126 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   3127 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   3128 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
   3129 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   3130 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   3131 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   3132 
   3133 /*
   3134 ** CAPI3REF: Number Of SQL Parameters
   3135 **
   3136 ** ^This routine can be used to find the number of [SQL parameters]
   3137 ** in a [prepared statement].  SQL parameters are tokens of the
   3138 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   3139 ** placeholders for values that are [sqlite3_bind_blob | bound]
   3140 ** to the parameters at a later time.
   3141 **
   3142 ** ^(This routine actually returns the index of the largest (rightmost)
   3143 ** parameter. For all forms except ?NNN, this will correspond to the
   3144 ** number of unique parameters.  If parameters of the ?NNN form are used,
   3145 ** there may be gaps in the list.)^
   3146 **
   3147 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3148 ** [sqlite3_bind_parameter_name()], and
   3149 ** [sqlite3_bind_parameter_index()].
   3150 */
   3151 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   3152 
   3153 /*
   3154 ** CAPI3REF: Name Of A Host Parameter
   3155 **
   3156 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   3157 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   3158 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3159 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3160 ** respectively.
   3161 ** In other words, the initial ":" or "$" or "@" or "?"
   3162 ** is included as part of the name.)^
   3163 ** ^Parameters of the form "?" without a following integer have no name
   3164 ** and are referred to as "nameless" or "anonymous parameters".
   3165 **
   3166 ** ^The first host parameter has an index of 1, not 0.
   3167 **
   3168 ** ^If the value N is out of range or if the N-th parameter is
   3169 ** nameless, then NULL is returned.  ^The returned string is
   3170 ** always in UTF-8 encoding even if the named parameter was
   3171 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
   3172 ** [sqlite3_prepare16_v2()].
   3173 **
   3174 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3175 ** [sqlite3_bind_parameter_count()], and
   3176 ** [sqlite3_bind_parameter_index()].
   3177 */
   3178 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   3179 
   3180 /*
   3181 ** CAPI3REF: Index Of A Parameter With A Given Name
   3182 **
   3183 ** ^Return the index of an SQL parameter given its name.  ^The
   3184 ** index value returned is suitable for use as the second
   3185 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   3186 ** is returned if no matching parameter is found.  ^The parameter
   3187 ** name must be given in UTF-8 even if the original statement
   3188 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
   3189 **
   3190 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3191 ** [sqlite3_bind_parameter_count()], and
   3192 ** [sqlite3_bind_parameter_index()].
   3193 */
   3194 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   3195 
   3196 /*
   3197 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   3198 **
   3199 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   3200 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   3201 ** ^Use this routine to reset all host parameters to NULL.
   3202 */
   3203 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   3204 
   3205 /*
   3206 ** CAPI3REF: Number Of Columns In A Result Set
   3207 **
   3208 ** ^Return the number of columns in the result set returned by the
   3209 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
   3210 ** statement that does not return data (for example an [UPDATE]).
   3211 */
   3212 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   3213 
   3214 /*
   3215 ** CAPI3REF: Column Names In A Result Set
   3216 **
   3217 ** ^These routines return the name assigned to a particular column
   3218 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   3219 ** interface returns a pointer to a zero-terminated UTF-8 string
   3220 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   3221 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   3222 ** that implements the [SELECT] statement. ^The second parameter is the
   3223 ** column number.  ^The leftmost column is number 0.
   3224 **
   3225 ** ^The returned string pointer is valid until either the [prepared statement]
   3226 ** is destroyed by [sqlite3_finalize()] or until the next call to
   3227 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   3228 **
   3229 ** ^If sqlite3_malloc() fails during the processing of either routine
   3230 ** (for example during a conversion from UTF-8 to UTF-16) then a
   3231 ** NULL pointer is returned.
   3232 **
   3233 ** ^The name of a result column is the value of the "AS" clause for
   3234 ** that column, if there is an AS clause.  If there is no AS clause
   3235 ** then the name of the column is unspecified and may change from
   3236 ** one release of SQLite to the next.
   3237 */
   3238 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   3239 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   3240 
   3241 /*
   3242 ** CAPI3REF: Source Of Data In A Query Result
   3243 **
   3244 ** ^These routines provide a means to determine the database, table, and
   3245 ** table column that is the origin of a particular result column in
   3246 ** [SELECT] statement.
   3247 ** ^The name of the database or table or column can be returned as
   3248 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   3249 ** the database name, the _table_ routines return the table name, and
   3250 ** the origin_ routines return the column name.
   3251 ** ^The returned string is valid until the [prepared statement] is destroyed
   3252 ** using [sqlite3_finalize()] or until the same information is requested
   3253 ** again in a different encoding.
   3254 **
   3255 ** ^The names returned are the original un-aliased names of the
   3256 ** database, table, and column.
   3257 **
   3258 ** ^The first argument to these interfaces is a [prepared statement].
   3259 ** ^These functions return information about the Nth result column returned by
   3260 ** the statement, where N is the second function argument.
   3261 ** ^The left-most column is column 0 for these routines.
   3262 **
   3263 ** ^If the Nth column returned by the statement is an expression or
   3264 ** subquery and is not a column value, then all of these functions return
   3265 ** NULL.  ^These routine might also return NULL if a memory allocation error
   3266 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   3267 ** or column that query result column was extracted from.
   3268 **
   3269 ** ^As with all other SQLite APIs, those whose names end with "16" return
   3270 ** UTF-16 encoded strings and the other functions return UTF-8.
   3271 **
   3272 ** ^These APIs are only available if the library was compiled with the
   3273 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   3274 **
   3275 ** If two or more threads call one or more of these routines against the same
   3276 ** prepared statement and column at the same time then the results are
   3277 ** undefined.
   3278 **
   3279 ** If two or more threads call one or more
   3280 ** [sqlite3_column_database_name | column metadata interfaces]
   3281 ** for the same [prepared statement] and result column
   3282 ** at the same time then the results are undefined.
   3283 */
   3284 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   3285 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   3286 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   3287 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   3288 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   3289 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   3290 
   3291 /*
   3292 ** CAPI3REF: Declared Datatype Of A Query Result
   3293 **
   3294 ** ^(The first parameter is a [prepared statement].
   3295 ** If this statement is a [SELECT] statement and the Nth column of the
   3296 ** returned result set of that [SELECT] is a table column (not an
   3297 ** expression or subquery) then the declared type of the table
   3298 ** column is returned.)^  ^If the Nth column of the result set is an
   3299 ** expression or subquery, then a NULL pointer is returned.
   3300 ** ^The returned string is always UTF-8 encoded.
   3301 **
   3302 ** ^(For example, given the database schema:
   3303 **
   3304 ** CREATE TABLE t1(c1 VARIANT);
   3305 **
   3306 ** and the following statement to be compiled:
   3307 **
   3308 ** SELECT c1 + 1, c1 FROM t1;
   3309 **
   3310 ** this routine would return the string "VARIANT" for the second result
   3311 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   3312 **
   3313 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   3314 ** is declared to contain a particular type does not mean that the
   3315 ** data stored in that column is of the declared type.  SQLite is
   3316 ** strongly typed, but the typing is dynamic not static.  ^Type
   3317 ** is associated with individual values, not with the containers
   3318 ** used to hold those values.
   3319 */
   3320 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   3321 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   3322 
   3323 /*
   3324 ** CAPI3REF: Evaluate An SQL Statement
   3325 **
   3326 ** After a [prepared statement] has been prepared using either
   3327 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
   3328 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   3329 ** must be called one or more times to evaluate the statement.
   3330 **
   3331 ** The details of the behavior of the sqlite3_step() interface depend
   3332 ** on whether the statement was prepared using the newer "v2" interface
   3333 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
   3334 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   3335 ** new "v2" interface is recommended for new applications but the legacy
   3336 ** interface will continue to be supported.
   3337 **
   3338 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   3339 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   3340 ** ^With the "v2" interface, any of the other [result codes] or
   3341 ** [extended result codes] might be returned as well.
   3342 **
   3343 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   3344 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   3345 ** or occurs outside of an explicit transaction, then you can retry the
   3346 ** statement.  If the statement is not a [COMMIT] and occurs within a
   3347 ** explicit transaction then you should rollback the transaction before
   3348 ** continuing.
   3349 **
   3350 ** ^[SQLITE_DONE] means that the statement has finished executing
   3351 ** successfully.  sqlite3_step() should not be called again on this virtual
   3352 ** machine without first calling [sqlite3_reset()] to reset the virtual
   3353 ** machine back to its initial state.
   3354 **
   3355 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   3356 ** is returned each time a new row of data is ready for processing by the
   3357 ** caller. The values may be accessed using the [column access functions].
   3358 ** sqlite3_step() is called again to retrieve the next row of data.
   3359 **
   3360 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   3361 ** violation) has occurred.  sqlite3_step() should not be called again on
   3362 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   3363 ** ^With the legacy interface, a more specific error code (for example,
   3364 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   3365 ** can be obtained by calling [sqlite3_reset()] on the
   3366 ** [prepared statement].  ^In the "v2" interface,
   3367 ** the more specific error code is returned directly by sqlite3_step().
   3368 **
   3369 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   3370 ** Perhaps it was called on a [prepared statement] that has
   3371 ** already been [sqlite3_finalize | finalized] or on one that had
   3372 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   3373 ** be the case that the same database connection is being used by two or
   3374 ** more threads at the same moment in time.
   3375 **
   3376 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   3377 ** API always returns a generic error code, [SQLITE_ERROR], following any
   3378 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   3379 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   3380 ** specific [error codes] that better describes the error.
   3381 ** We admit that this is a goofy design.  The problem has been fixed
   3382 ** with the "v2" interface.  If you prepare all of your SQL statements
   3383 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
   3384 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   3385 ** then the more specific [error codes] are returned directly
   3386 ** by sqlite3_step().  The use of the "v2" interface is recommended.
   3387 */
   3388 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   3389 
   3390 /*
   3391 ** CAPI3REF: Number of columns in a result set
   3392 **
   3393 ** ^The sqlite3_data_count(P) the number of columns in the
   3394 ** of the result set of [prepared statement] P.
   3395 */
   3396 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   3397 
   3398 /*
   3399 ** CAPI3REF: Fundamental Datatypes
   3400 ** KEYWORDS: SQLITE_TEXT
   3401 **
   3402 ** ^(Every value in SQLite has one of five fundamental datatypes:
   3403 **
   3404 ** <ul>
   3405 ** <li> 64-bit signed integer
   3406 ** <li> 64-bit IEEE floating point number
   3407 ** <li> string
   3408 ** <li> BLOB
   3409 ** <li> NULL
   3410 ** </ul>)^
   3411 **
   3412 ** These constants are codes for each of those types.
   3413 **
   3414 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   3415 ** for a completely different meaning.  Software that links against both
   3416 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   3417 ** SQLITE_TEXT.
   3418 */
   3419 #define SQLITE_INTEGER  1
   3420 #define SQLITE_FLOAT    2
   3421 #define SQLITE_BLOB     4
   3422 #define SQLITE_NULL     5
   3423 #ifdef SQLITE_TEXT
   3424 # undef SQLITE_TEXT
   3425 #else
   3426 # define SQLITE_TEXT     3
   3427 #endif
   3428 #define SQLITE3_TEXT     3
   3429 
   3430 /*
   3431 ** CAPI3REF: Result Values From A Query
   3432 ** KEYWORDS: {column access functions}
   3433 **
   3434 ** These routines form the "result set" interface.
   3435 **
   3436 ** ^These routines return information about a single column of the current
   3437 ** result row of a query.  ^In every case the first argument is a pointer
   3438 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   3439 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   3440 ** and the second argument is the index of the column for which information
   3441 ** should be returned. ^The leftmost column of the result set has the index 0.
   3442 ** ^The number of columns in the result can be determined using
   3443 ** [sqlite3_column_count()].
   3444 **
   3445 ** If the SQL statement does not currently point to a valid row, or if the
   3446 ** column index is out of range, the result is undefined.
   3447 ** These routines may only be called when the most recent call to
   3448 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   3449 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   3450 ** If any of these routines are called after [sqlite3_reset()] or
   3451 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   3452 ** something other than [SQLITE_ROW], the results are undefined.
   3453 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   3454 ** are called from a different thread while any of these routines
   3455 ** are pending, then the results are undefined.
   3456 **
   3457 ** ^The sqlite3_column_type() routine returns the
   3458 ** [SQLITE_INTEGER | datatype code] for the initial data type
   3459 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   3460 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
   3461 ** returned by sqlite3_column_type() is only meaningful if no type
   3462 ** conversions have occurred as described below.  After a type conversion,
   3463 ** the value returned by sqlite3_column_type() is undefined.  Future
   3464 ** versions of SQLite may change the behavior of sqlite3_column_type()
   3465 ** following a type conversion.
   3466 **
   3467 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   3468 ** routine returns the number of bytes in that BLOB or string.
   3469 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   3470 ** the string to UTF-8 and then returns the number of bytes.
   3471 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   3472 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   3473 ** the number of bytes in that string.
   3474 ** ^The value returned does not include the zero terminator at the end
   3475 ** of the string.  ^For clarity: the value returned is the number of
   3476 ** bytes in the string, not the number of characters.
   3477 **
   3478 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   3479 ** even empty strings, are always zero terminated.  ^The return
   3480 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
   3481 ** pointer, possibly even a NULL pointer.
   3482 **
   3483 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
   3484 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
   3485 ** ^The zero terminator is not included in this count.
   3486 **
   3487 ** ^The object returned by [sqlite3_column_value()] is an
   3488 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
   3489 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
   3490 ** If the [unprotected sqlite3_value] object returned by
   3491 ** [sqlite3_column_value()] is used in any other way, including calls
   3492 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   3493 ** or [sqlite3_value_bytes()], then the behavior is undefined.
   3494 **
   3495 ** These routines attempt to convert the value where appropriate.  ^For
   3496 ** example, if the internal representation is FLOAT and a text result
   3497 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   3498 ** conversion automatically.  ^(The following table details the conversions
   3499 ** that are applied:
   3500 **
   3501 ** <blockquote>
   3502 ** <table border="1">
   3503 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   3504 **
   3505 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   3506 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   3507 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
   3508 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
   3509 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   3510 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   3511 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   3512 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
   3513 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   3514 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
   3515 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
   3516 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
   3517 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   3518 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
   3519 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
   3520 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   3521 ** </table>
   3522 ** </blockquote>)^
   3523 **
   3524 ** The table above makes reference to standard C library functions atoi()
   3525 ** and atof().  SQLite does not really use these functions.  It has its
   3526 ** own equivalent internal routines.  The atoi() and atof() names are
   3527 ** used in the table for brevity and because they are familiar to most
   3528 ** C programmers.
   3529 **
   3530 ** ^Note that when type conversions occur, pointers returned by prior
   3531 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   3532 ** sqlite3_column_text16() may be invalidated.
   3533 ** ^(Type conversions and pointer invalidations might occur
   3534 ** in the following cases:
   3535 **
   3536 ** <ul>
   3537 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   3538 **      sqlite3_column_text16() is called.  A zero-terminator might
   3539 **      need to be added to the string.</li>
   3540 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   3541 **      sqlite3_column_text16() is called.  The content must be converted
   3542 **      to UTF-16.</li>
   3543 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   3544 **      sqlite3_column_text() is called.  The content must be converted
   3545 **      to UTF-8.</li>
   3546 ** </ul>)^
   3547 **
   3548 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   3549 ** not invalidate a prior pointer, though of course the content of the buffer
   3550 ** that the prior pointer points to will have been modified.  Other kinds
   3551 ** of conversion are done in place when it is possible, but sometimes they
   3552 ** are not possible and in those cases prior pointers are invalidated.
   3553 **
   3554 ** ^(The safest and easiest to remember policy is to invoke these routines
   3555 ** in one of the following ways:
   3556 **
   3557 ** <ul>
   3558 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   3559 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   3560 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   3561 ** </ul>)^
   3562 **
   3563 ** In other words, you should call sqlite3_column_text(),
   3564 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   3565 ** into the desired format, then invoke sqlite3_column_bytes() or
   3566 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   3567 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   3568 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   3569 ** with calls to sqlite3_column_bytes().
   3570 **
   3571 ** ^The pointers returned are valid until a type conversion occurs as
   3572 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   3573 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   3574 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
   3575 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   3576 ** [sqlite3_free()].
   3577 **
   3578 ** ^(If a memory allocation error occurs during the evaluation of any
   3579 ** of these routines, a default value is returned.  The default value
   3580 ** is either the integer 0, the floating point number 0.0, or a NULL
   3581 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   3582 ** [SQLITE_NOMEM].)^
   3583 */
   3584 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   3585 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   3586 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   3587 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   3588 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   3589 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   3590 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   3591 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   3592 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   3593 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   3594 
   3595 /*
   3596 ** CAPI3REF: Destroy A Prepared Statement Object
   3597 **
   3598 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   3599 ** ^If the statement was executed successfully or not executed at all, then
   3600 ** SQLITE_OK is returned. ^If execution of the statement failed then an
   3601 ** [error code] or [extended error code] is returned.
   3602 **
   3603 ** ^This routine can be called at any point during the execution of the
   3604 ** [prepared statement].  ^If the virtual machine has not
   3605 ** completed execution when this routine is called, that is like
   3606 ** encountering an error or an [sqlite3_interrupt | interrupt].
   3607 ** ^Incomplete updates may be rolled back and transactions canceled,
   3608 ** depending on the circumstances, and the
   3609 ** [error code] returned will be [SQLITE_ABORT].
   3610 */
   3611 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   3612 
   3613 /*
   3614 ** CAPI3REF: Reset A Prepared Statement Object
   3615 **
   3616 ** The sqlite3_reset() function is called to reset a [prepared statement]
   3617 ** object back to its initial state, ready to be re-executed.
   3618 ** ^Any SQL statement variables that had values bound to them using
   3619 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   3620 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   3621 **
   3622 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   3623 ** back to the beginning of its program.
   3624 **
   3625 ** ^If the most recent call to [sqlite3_step(S)] for the
   3626 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   3627 ** or if [sqlite3_step(S)] has never before been called on S,
   3628 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   3629 **
   3630 ** ^If the most recent call to [sqlite3_step(S)] for the
   3631 ** [prepared statement] S indicated an error, then
   3632 ** [sqlite3_reset(S)] returns an appropriate [error code].
   3633 **
   3634 ** ^The [sqlite3_reset(S)] interface does not change the values
   3635 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   3636 */
   3637 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   3638 
   3639 /*
   3640 ** CAPI3REF: Create Or Redefine SQL Functions
   3641 ** KEYWORDS: {function creation routines}
   3642 ** KEYWORDS: {application-defined SQL function}
   3643 ** KEYWORDS: {application-defined SQL functions}
   3644 **
   3645 ** ^These two functions (collectively known as "function creation routines")
   3646 ** are used to add SQL functions or aggregates or to redefine the behavior
   3647 ** of existing SQL functions or aggregates.  The only difference between the
   3648 ** two is that the second parameter, the name of the (scalar) function or
   3649 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
   3650 ** for sqlite3_create_function16().
   3651 **
   3652 ** ^The first parameter is the [database connection] to which the SQL
   3653 ** function is to be added.  ^If an application uses more than one database
   3654 ** connection then application-defined SQL functions must be added
   3655 ** to each database connection separately.
   3656 **
   3657 ** The second parameter is the name of the SQL function to be created or
   3658 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
   3659 ** the zero-terminator.  Note that the name length limit is in bytes, not
   3660 ** characters.  ^Any attempt to create a function with a longer name
   3661 ** will result in [SQLITE_ERROR] being returned.
   3662 **
   3663 ** ^The third parameter (nArg)
   3664 ** is the number of arguments that the SQL function or
   3665 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   3666 ** aggregate may take any number of arguments between 0 and the limit
   3667 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   3668 ** parameter is less than -1 or greater than 127 then the behavior is
   3669 ** undefined.
   3670 **
   3671 ** The fourth parameter, eTextRep, specifies what
   3672 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   3673 ** its parameters.  Any SQL function implementation should be able to work
   3674 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
   3675 ** more efficient with one encoding than another.  ^An application may
   3676 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
   3677 ** times with the same function but with different values of eTextRep.
   3678 ** ^When multiple implementations of the same function are available, SQLite
   3679 ** will pick the one that involves the least amount of data conversion.
   3680 ** If there is only a single implementation which does not care what text
   3681 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
   3682 **
   3683 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   3684 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   3685 **
   3686 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
   3687 ** pointers to C-language functions that implement the SQL function or
   3688 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   3689 ** callback only; NULL pointers should be passed as the xStep and xFinal
   3690 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   3691 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
   3692 ** SQL function or aggregate, pass NULL for all three function callbacks.
   3693 **
   3694 ** ^It is permitted to register multiple implementations of the same
   3695 ** functions with the same name but with either differing numbers of
   3696 ** arguments or differing preferred text encodings.  ^SQLite will use
   3697 ** the implementation that most closely matches the way in which the
   3698 ** SQL function is used.  ^A function implementation with a non-negative
   3699 ** nArg parameter is a better match than a function implementation with
   3700 ** a negative nArg.  ^A function where the preferred text encoding
   3701 ** matches the database encoding is a better
   3702 ** match than a function where the encoding is different.
   3703 ** ^A function where the encoding difference is between UTF16le and UTF16be
   3704 ** is a closer match than a function where the encoding difference is
   3705 ** between UTF8 and UTF16.
   3706 **
   3707 ** ^Built-in functions may be overloaded by new application-defined functions.
   3708 ** ^The first application-defined function with a given name overrides all
   3709 ** built-in functions in the same [database connection] with the same name.
   3710 ** ^Subsequent application-defined functions of the same name only override
   3711 ** prior application-defined functions that are an exact match for the
   3712 ** number of parameters and preferred encoding.
   3713 **
   3714 ** ^An application-defined function is permitted to call other
   3715 ** SQLite interfaces.  However, such calls must not
   3716 ** close the database connection nor finalize or reset the prepared
   3717 ** statement in which the function is running.
   3718 */
   3719 SQLITE_API int sqlite3_create_function(
   3720   sqlite3 *db,
   3721   const char *zFunctionName,
   3722   int nArg,
   3723   int eTextRep,
   3724   void *pApp,
   3725   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   3726   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   3727   void (*xFinal)(sqlite3_context*)
   3728 );
   3729 SQLITE_API int sqlite3_create_function16(
   3730   sqlite3 *db,
   3731   const void *zFunctionName,
   3732   int nArg,
   3733   int eTextRep,
   3734   void *pApp,
   3735   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   3736   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   3737   void (*xFinal)(sqlite3_context*)
   3738 );
   3739 
   3740 /*
   3741 ** CAPI3REF: Text Encodings
   3742 **
   3743 ** These constant define integer codes that represent the various
   3744 ** text encodings supported by SQLite.
   3745 */
   3746 #define SQLITE_UTF8           1
   3747 #define SQLITE_UTF16LE        2
   3748 #define SQLITE_UTF16BE        3
   3749 #define SQLITE_UTF16          4    /* Use native byte order */
   3750 #define SQLITE_ANY            5    /* sqlite3_create_function only */
   3751 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   3752 
   3753 /*
   3754 ** CAPI3REF: Deprecated Functions
   3755 ** DEPRECATED
   3756 **
   3757 ** These functions are [deprecated].  In order to maintain
   3758 ** backwards compatibility with older code, these functions continue
   3759 ** to be supported.  However, new applications should avoid
   3760 ** the use of these functions.  To help encourage people to avoid
   3761 ** using these functions, we are not going to tell you what they do.
   3762 */
   3763 #ifndef SQLITE_OMIT_DEPRECATED
   3764 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   3765 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   3766 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   3767 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   3768 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   3769 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
   3770 #endif
   3771 
   3772 /*
   3773 ** CAPI3REF: Obtaining SQL Function Parameter Values
   3774 **
   3775 ** The C-language implementation of SQL functions and aggregates uses
   3776 ** this set of interface routines to access the parameter values on
   3777 ** the function or aggregate.
   3778 **
   3779 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
   3780 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
   3781 ** define callbacks that implement the SQL functions and aggregates.
   3782 ** The 4th parameter to these callbacks is an array of pointers to
   3783 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
   3784 ** each parameter to the SQL function.  These routines are used to
   3785 ** extract values from the [sqlite3_value] objects.
   3786 **
   3787 ** These routines work only with [protected sqlite3_value] objects.
   3788 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   3789 ** object results in undefined behavior.
   3790 **
   3791 ** ^These routines work just like the corresponding [column access functions]
   3792 ** except that  these routines take a single [protected sqlite3_value] object
   3793 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   3794 **
   3795 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   3796 ** in the native byte-order of the host machine.  ^The
   3797 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   3798 ** extract UTF-16 strings as big-endian and little-endian respectively.
   3799 **
   3800 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   3801 ** numeric affinity to the value.  This means that an attempt is
   3802 ** made to convert the value to an integer or floating point.  If
   3803 ** such a conversion is possible without loss of information (in other
   3804 ** words, if the value is a string that looks like a number)
   3805 ** then the conversion is performed.  Otherwise no conversion occurs.
   3806 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   3807 **
   3808 ** Please pay particular attention to the fact that the pointer returned
   3809 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   3810 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   3811 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   3812 ** or [sqlite3_value_text16()].
   3813 **
   3814 ** These routines must be called from the same thread as
   3815 ** the SQL function that supplied the [sqlite3_value*] parameters.
   3816 */
   3817 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   3818 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   3819 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   3820 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   3821 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   3822 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   3823 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   3824 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   3825 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   3826 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   3827 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   3828 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   3829 
   3830 /*
   3831 ** CAPI3REF: Obtain Aggregate Function Context
   3832 **
   3833 ** Implementions of aggregate SQL functions use this
   3834 ** routine to allocate memory for storing their state.
   3835 **
   3836 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   3837 ** for a particular aggregate function, SQLite
   3838 ** allocates N of memory, zeroes out that memory, and returns a pointer
   3839 ** to the new memory. ^On second and subsequent calls to
   3840 ** sqlite3_aggregate_context() for the same aggregate function instance,
   3841 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   3842 ** called once for each invocation of the xStep callback and then one
   3843 ** last time when the xFinal callback is invoked.  ^(When no rows match
   3844 ** an aggregate query, the xStep() callback of the aggregate function
   3845 ** implementation is never called and xFinal() is called exactly once.
   3846 ** In those cases, sqlite3_aggregate_context() might be called for the
   3847 ** first time from within xFinal().)^
   3848 **
   3849 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
   3850 ** less than or equal to zero or if a memory allocate error occurs.
   3851 **
   3852 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   3853 ** determined by the N parameter on first successful call.  Changing the
   3854 ** value of N in subsequent call to sqlite3_aggregate_context() within
   3855 ** the same aggregate function instance will not resize the memory
   3856 ** allocation.)^
   3857 **
   3858 ** ^SQLite automatically frees the memory allocated by
   3859 ** sqlite3_aggregate_context() when the aggregate query concludes.
   3860 **
   3861 ** The first parameter must be a copy of the
   3862 ** [sqlite3_context | SQL function context] that is the first parameter
   3863 ** to the xStep or xFinal callback routine that implements the aggregate
   3864 ** function.
   3865 **
   3866 ** This routine must be called from the same thread in which
   3867 ** the aggregate SQL function is running.
   3868 */
   3869 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   3870 
   3871 /*
   3872 ** CAPI3REF: User Data For Functions
   3873 **
   3874 ** ^The sqlite3_user_data() interface returns a copy of
   3875 ** the pointer that was the pUserData parameter (the 5th parameter)
   3876 ** of the [sqlite3_create_function()]
   3877 ** and [sqlite3_create_function16()] routines that originally
   3878 ** registered the application defined function.
   3879 **
   3880 ** This routine must be called from the same thread in which
   3881 ** the application-defined function is running.
   3882 */
   3883 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   3884 
   3885 /*
   3886 ** CAPI3REF: Database Connection For Functions
   3887 **
   3888 ** ^The sqlite3_context_db_handle() interface returns a copy of
   3889 ** the pointer to the [database connection] (the 1st parameter)
   3890 ** of the [sqlite3_create_function()]
   3891 ** and [sqlite3_create_function16()] routines that originally
   3892 ** registered the application defined function.
   3893 */
   3894 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   3895 
   3896 /*
   3897 ** CAPI3REF: Function Auxiliary Data
   3898 **
   3899 ** The following two functions may be used by scalar SQL functions to
   3900 ** associate metadata with argument values. If the same value is passed to
   3901 ** multiple invocations of the same SQL function during query execution, under
   3902 ** some circumstances the associated metadata may be preserved. This may
   3903 ** be used, for example, to add a regular-expression matching scalar
   3904 ** function. The compiled version of the regular expression is stored as
   3905 ** metadata associated with the SQL value passed as the regular expression
   3906 ** pattern.  The compiled regular expression can be reused on multiple
   3907 ** invocations of the same function so that the original pattern string
   3908 ** does not need to be recompiled on each invocation.
   3909 **
   3910 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
   3911 ** associated by the sqlite3_set_auxdata() function with the Nth argument
   3912 ** value to the application-defined function. ^If no metadata has been ever
   3913 ** been set for the Nth argument of the function, or if the corresponding
   3914 ** function parameter has changed since the meta-data was set,
   3915 ** then sqlite3_get_auxdata() returns a NULL pointer.
   3916 **
   3917 ** ^The sqlite3_set_auxdata() interface saves the metadata
   3918 ** pointed to by its 3rd parameter as the metadata for the N-th
   3919 ** argument of the application-defined function.  Subsequent
   3920 ** calls to sqlite3_get_auxdata() might return this data, if it has
   3921 ** not been destroyed.
   3922 ** ^If it is not NULL, SQLite will invoke the destructor
   3923 ** function given by the 4th parameter to sqlite3_set_auxdata() on
   3924 ** the metadata when the corresponding function parameter changes
   3925 ** or when the SQL statement completes, whichever comes first.
   3926 **
   3927 ** SQLite is free to call the destructor and drop metadata on any
   3928 ** parameter of any function at any time.  ^The only guarantee is that
   3929 ** the destructor will be called before the metadata is dropped.
   3930 **
   3931 ** ^(In practice, metadata is preserved between function calls for
   3932 ** expressions that are constant at compile time. This includes literal
   3933 ** values and [parameters].)^
   3934 **
   3935 ** These routines must be called from the same thread in which
   3936 ** the SQL function is running.
   3937 */
   3938 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   3939 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   3940 
   3941 
   3942 /*
   3943 ** CAPI3REF: Constants Defining Special Destructor Behavior
   3944 **
   3945 ** These are special values for the destructor that is passed in as the
   3946 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   3947 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   3948 ** and will never change.  It does not need to be destroyed.  ^The
   3949 ** SQLITE_TRANSIENT value means that the content will likely change in
   3950 ** the near future and that SQLite should make its own private copy of
   3951 ** the content before returning.
   3952 **
   3953 ** The typedef is necessary to work around problems in certain
   3954 ** C++ compilers.  See ticket #2191.
   3955 */
   3956 typedef void (*sqlite3_destructor_type)(void*);
   3957 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   3958 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   3959 
   3960 /*
   3961 ** CAPI3REF: Setting The Result Of An SQL Function
   3962 **
   3963 ** These routines are used by the xFunc or xFinal callbacks that
   3964 ** implement SQL functions and aggregates.  See
   3965 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   3966 ** for additional information.
   3967 **
   3968 ** These functions work very much like the [parameter binding] family of
   3969 ** functions used to bind values to host parameters in prepared statements.
   3970 ** Refer to the [SQL parameter] documentation for additional information.
   3971 **
   3972 ** ^The sqlite3_result_blob() interface sets the result from
   3973 ** an application-defined function to be the BLOB whose content is pointed
   3974 ** to by the second parameter and which is N bytes long where N is the
   3975 ** third parameter.
   3976 **
   3977 ** ^The sqlite3_result_zeroblob() interfaces set the result of
   3978 ** the application-defined function to be a BLOB containing all zero
   3979 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
   3980 **
   3981 ** ^The sqlite3_result_double() interface sets the result from
   3982 ** an application-defined function to be a floating point value specified
   3983 ** by its 2nd argument.
   3984 **
   3985 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   3986 ** cause the implemented SQL function to throw an exception.
   3987 ** ^SQLite uses the string pointed to by the
   3988 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   3989 ** as the text of an error message.  ^SQLite interprets the error
   3990 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   3991 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   3992 ** byte order.  ^If the third parameter to sqlite3_result_error()
   3993 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   3994 ** message all text up through the first zero character.
   3995 ** ^If the third parameter to sqlite3_result_error() or
   3996 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   3997 ** bytes (not characters) from the 2nd parameter as the error message.
   3998 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   3999 ** routines make a private copy of the error message text before
   4000 ** they return.  Hence, the calling function can deallocate or
   4001 ** modify the text after they return without harm.
   4002 ** ^The sqlite3_result_error_code() function changes the error code
   4003 ** returned by SQLite as a result of an error in a function.  ^By default,
   4004 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   4005 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   4006 **
   4007 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
   4008 ** indicating that a string or BLOB is too long to represent.
   4009 **
   4010 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
   4011 ** indicating that a memory allocation failed.
   4012 **
   4013 ** ^The sqlite3_result_int() interface sets the return value
   4014 ** of the application-defined function to be the 32-bit signed integer
   4015 ** value given in the 2nd argument.
   4016 ** ^The sqlite3_result_int64() interface sets the return value
   4017 ** of the application-defined function to be the 64-bit signed integer
   4018 ** value given in the 2nd argument.
   4019 **
   4020 ** ^The sqlite3_result_null() interface sets the return value
   4021 ** of the application-defined function to be NULL.
   4022 **
   4023 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   4024 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   4025 ** set the return value of the application-defined function to be
   4026 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   4027 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   4028 ** ^SQLite takes the text result from the application from
   4029 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   4030 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4031 ** is negative, then SQLite takes result text from the 2nd parameter
   4032 ** through the first zero character.
   4033 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4034 ** is non-negative, then as many bytes (not characters) of the text
   4035 ** pointed to by the 2nd parameter are taken as the application-defined
   4036 ** function result.
   4037 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4038 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   4039 ** function as the destructor on the text or BLOB result when it has
   4040 ** finished using that result.
   4041 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   4042 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   4043 ** assumes that the text or BLOB result is in constant space and does not
   4044 ** copy the content of the parameter nor call a destructor on the content
   4045 ** when it has finished using that result.
   4046 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4047 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   4048 ** then SQLite makes a copy of the result into space obtained from
   4049 ** from [sqlite3_malloc()] before it returns.
   4050 **
   4051 ** ^The sqlite3_result_value() interface sets the result of
   4052 ** the application-defined function to be a copy the
   4053 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   4054 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   4055 ** so that the [sqlite3_value] specified in the parameter may change or
   4056 ** be deallocated after sqlite3_result_value() returns without harm.
   4057 ** ^A [protected sqlite3_value] object may always be used where an
   4058 ** [unprotected sqlite3_value] object is required, so either
   4059 ** kind of [sqlite3_value] object can be used with this interface.
   4060 **
   4061 ** If these routines are called from within the different thread
   4062 ** than the one containing the application-defined function that received
   4063 ** the [sqlite3_context] pointer, the results are undefined.
   4064 */
   4065 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   4066 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   4067 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   4068 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   4069 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   4070 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   4071 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   4072 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   4073 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   4074 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   4075 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   4076 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   4077 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   4078 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   4079 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   4080 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   4081 
   4082 /*
   4083 ** CAPI3REF: Define New Collating Sequences
   4084 **
   4085 ** These functions are used to add new collation sequences to the
   4086 ** [database connection] specified as the first argument.
   4087 **
   4088 ** ^The name of the new collation sequence is specified as a UTF-8 string
   4089 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   4090 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
   4091 ** the name is passed as the second function argument.
   4092 **
   4093 ** ^The third argument may be one of the constants [SQLITE_UTF8],
   4094 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
   4095 ** routine expects to be passed pointers to strings encoded using UTF-8,
   4096 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
   4097 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
   4098 ** expects pointers to be UTF-16 strings in the native byte order, or the
   4099 ** argument can be [SQLITE_UTF16_ALIGNED] if the
   4100 ** the routine expects pointers to 16-bit word aligned strings
   4101 ** of UTF-16 in the native byte order.
   4102 **
   4103 ** A pointer to the user supplied routine must be passed as the fifth
   4104 ** argument.  ^If it is NULL, this is the same as deleting the collation
   4105 ** sequence (so that SQLite cannot call it anymore).
   4106 ** ^Each time the application supplied function is invoked, it is passed
   4107 ** as its first parameter a copy of the void* passed as the fourth argument
   4108 ** to sqlite3_create_collation() or sqlite3_create_collation16().
   4109 **
   4110 ** ^The remaining arguments to the application-supplied routine are two strings,
   4111 ** each represented by a (length, data) pair and encoded in the encoding
   4112 ** that was passed as the third argument when the collation sequence was
   4113 ** registered.  The application defined collation routine should
   4114 ** return negative, zero or positive if the first string is less than,
   4115 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
   4116 **
   4117 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   4118 ** except that it takes an extra argument which is a destructor for
   4119 ** the collation.  ^The destructor is called when the collation is
   4120 ** destroyed and is passed a copy of the fourth parameter void* pointer
   4121 ** of the sqlite3_create_collation_v2().
   4122 ** ^Collations are destroyed when they are overridden by later calls to the
   4123 ** collation creation functions or when the [database connection] is closed
   4124 ** using [sqlite3_close()].
   4125 **
   4126 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   4127 */
   4128 SQLITE_API int sqlite3_create_collation(
   4129   sqlite3*,
   4130   const char *zName,
   4131   int eTextRep,
   4132   void*,
   4133   int(*xCompare)(void*,int,const void*,int,const void*)
   4134 );
   4135 SQLITE_API int sqlite3_create_collation_v2(
   4136   sqlite3*,
   4137   const char *zName,
   4138   int eTextRep,
   4139   void*,
   4140   int(*xCompare)(void*,int,const void*,int,const void*),
   4141   void(*xDestroy)(void*)
   4142 );
   4143 SQLITE_API int sqlite3_create_collation16(
   4144   sqlite3*,
   4145   const void *zName,
   4146   int eTextRep,
   4147   void*,
   4148   int(*xCompare)(void*,int,const void*,int,const void*)
   4149 );
   4150 
   4151 /*
   4152 ** CAPI3REF: Collation Needed Callbacks
   4153 **
   4154 ** ^To avoid having to register all collation sequences before a database
   4155 ** can be used, a single callback function may be registered with the
   4156 ** [database connection] to be invoked whenever an undefined collation
   4157 ** sequence is required.
   4158 **
   4159 ** ^If the function is registered using the sqlite3_collation_needed() API,
   4160 ** then it is passed the names of undefined collation sequences as strings
   4161 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   4162 ** the names are passed as UTF-16 in machine native byte order.
   4163 ** ^A call to either function replaces the existing collation-needed callback.
   4164 **
   4165 ** ^(When the callback is invoked, the first argument passed is a copy
   4166 ** of the second argument to sqlite3_collation_needed() or
   4167 ** sqlite3_collation_needed16().  The second argument is the database
   4168 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   4169 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   4170 ** sequence function required.  The fourth parameter is the name of the
   4171 ** required collation sequence.)^
   4172 **
   4173 ** The callback function should register the desired collation using
   4174 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   4175 ** [sqlite3_create_collation_v2()].
   4176 */
   4177 SQLITE_API int sqlite3_collation_needed(
   4178   sqlite3*,
   4179   void*,
   4180   void(*)(void*,sqlite3*,int eTextRep,const char*)
   4181 );
   4182 SQLITE_API int sqlite3_collation_needed16(
   4183   sqlite3*,
   4184   void*,
   4185   void(*)(void*,sqlite3*,int eTextRep,const void*)
   4186 );
   4187 
   4188 /*
   4189 ** Specify the key for an encrypted database.  This routine should be
   4190 ** called right after sqlite3_open().
   4191 **
   4192 ** The code to implement this API is not available in the public release
   4193 ** of SQLite.
   4194 */
   4195 SQLITE_API int sqlite3_key(
   4196   sqlite3 *db,                   /* Database to be rekeyed */
   4197   const void *pKey, int nKey     /* The key */
   4198 );
   4199 
   4200 /*
   4201 ** Change the key on an open database.  If the current database is not
   4202 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   4203 ** database is decrypted.
   4204 **
   4205 ** The code to implement this API is not available in the public release
   4206 ** of SQLite.
   4207 */
   4208 SQLITE_API int sqlite3_rekey(
   4209   sqlite3 *db,                   /* Database to be rekeyed */
   4210   const void *pKey, int nKey     /* The new key */
   4211 );
   4212 
   4213 /*
   4214 ** CAPI3REF: Suspend Execution For A Short Time
   4215 **
   4216 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
   4217 ** for at least a number of milliseconds specified in its parameter.
   4218 **
   4219 ** ^If the operating system does not support sleep requests with
   4220 ** millisecond time resolution, then the time will be rounded up to
   4221 ** the nearest second. ^The number of milliseconds of sleep actually
   4222 ** requested from the operating system is returned.
   4223 **
   4224 ** ^SQLite implements this interface by calling the xSleep()
   4225 ** method of the default [sqlite3_vfs] object.
   4226 */
   4227 SQLITE_API int sqlite3_sleep(int);
   4228 
   4229 /*
   4230 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   4231 **
   4232 ** ^(If this global variable is made to point to a string which is
   4233 ** the name of a folder (a.k.a. directory), then all temporary files
   4234 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   4235 ** will be placed in that directory.)^  ^If this variable
   4236 ** is a NULL pointer, then SQLite performs a search for an appropriate
   4237 ** temporary file directory.
   4238 **
   4239 ** It is not safe to read or modify this variable in more than one
   4240 ** thread at a time.  It is not safe to read or modify this variable
   4241 ** if a [database connection] is being used at the same time in a separate
   4242 ** thread.
   4243 ** It is intended that this variable be set once
   4244 ** as part of process initialization and before any SQLite interface
   4245 ** routines have been called and that this variable remain unchanged
   4246 ** thereafter.
   4247 **
   4248 ** ^The [temp_store_directory pragma] may modify this variable and cause
   4249 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4250 ** the [temp_store_directory pragma] always assumes that any string
   4251 ** that this variable points to is held in memory obtained from
   4252 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4253 ** using [sqlite3_free].
   4254 ** Hence, if this variable is modified directly, either it should be
   4255 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4256 ** or else the use of the [temp_store_directory pragma] should be avoided.
   4257 */
   4258 SQLITE_API char *sqlite3_temp_directory;
   4259 
   4260 /*
   4261 ** CAPI3REF: Test For Auto-Commit Mode
   4262 ** KEYWORDS: {autocommit mode}
   4263 **
   4264 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   4265 ** zero if the given database connection is or is not in autocommit mode,
   4266 ** respectively.  ^Autocommit mode is on by default.
   4267 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   4268 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   4269 **
   4270 ** If certain kinds of errors occur on a statement within a multi-statement
   4271 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   4272 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   4273 ** transaction might be rolled back automatically.  The only way to
   4274 ** find out whether SQLite automatically rolled back the transaction after
   4275 ** an error is to use this function.
   4276 **
   4277 ** If another thread changes the autocommit status of the database
   4278 ** connection while this routine is running, then the return value
   4279 ** is undefined.
   4280 */
   4281 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   4282 
   4283 /*
   4284 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   4285 **
   4286 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   4287 ** to which a [prepared statement] belongs.  ^The [database connection]
   4288 ** returned by sqlite3_db_handle is the same [database connection]
   4289 ** that was the first argument
   4290 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   4291 ** create the statement in the first place.
   4292 */
   4293 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   4294 
   4295 /*
   4296 ** CAPI3REF: Find the next prepared statement
   4297 **
   4298 ** ^This interface returns a pointer to the next [prepared statement] after
   4299 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   4300 ** then this interface returns a pointer to the first prepared statement
   4301 ** associated with the database connection pDb.  ^If no prepared statement
   4302 ** satisfies the conditions of this routine, it returns NULL.
   4303 **
   4304 ** The [database connection] pointer D in a call to
   4305 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   4306 ** connection and in particular must not be a NULL pointer.
   4307 */
   4308 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   4309 
   4310 /*
   4311 ** CAPI3REF: Commit And Rollback Notification Callbacks
   4312 **
   4313 ** ^The sqlite3_commit_hook() interface registers a callback
   4314 ** function to be invoked whenever a transaction is [COMMIT | committed].
   4315 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   4316 ** for the same database connection is overridden.
   4317 ** ^The sqlite3_rollback_hook() interface registers a callback
   4318 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   4319 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   4320 ** for the same database connection is overridden.
   4321 ** ^The pArg argument is passed through to the callback.
   4322 ** ^If the callback on a commit hook function returns non-zero,
   4323 ** then the commit is converted into a rollback.
   4324 **
   4325 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   4326 ** return the P argument from the previous call of the same function
   4327 ** on the same [database connection] D, or NULL for
   4328 ** the first call for each function on D.
   4329 **
   4330 ** The callback implementation must not do anything that will modify
   4331 ** the database connection that invoked the callback.  Any actions
   4332 ** to modify the database connection must be deferred until after the
   4333 ** completion of the [sqlite3_step()] call that triggered the commit
   4334 ** or rollback hook in the first place.
   4335 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4336 ** database connections for the meaning of "modify" in this paragraph.
   4337 **
   4338 ** ^Registering a NULL function disables the callback.
   4339 **
   4340 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   4341 ** operation is allowed to continue normally.  ^If the commit hook
   4342 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   4343 ** ^The rollback hook is invoked on a rollback that results from a commit
   4344 ** hook returning non-zero, just as it would be with any other rollback.
   4345 **
   4346 ** ^For the purposes of this API, a transaction is said to have been
   4347 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   4348 ** an error or constraint causes an implicit rollback to occur.
   4349 ** ^The rollback callback is not invoked if a transaction is
   4350 ** automatically rolled back because the database connection is closed.
   4351 ** ^The rollback callback is not invoked if a transaction is
   4352 ** rolled back because a commit callback returned non-zero.
   4353 **
   4354 ** See also the [sqlite3_update_hook()] interface.
   4355 */
   4356 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   4357 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   4358 
   4359 /*
   4360 ** CAPI3REF: Data Change Notification Callbacks
   4361 **
   4362 ** ^The sqlite3_update_hook() interface registers a callback function
   4363 ** with the [database connection] identified by the first argument
   4364 ** to be invoked whenever a row is updated, inserted or deleted.
   4365 ** ^Any callback set by a previous call to this function
   4366 ** for the same database connection is overridden.
   4367 **
   4368 ** ^The second argument is a pointer to the function to invoke when a
   4369 ** row is updated, inserted or deleted.
   4370 ** ^The first argument to the callback is a copy of the third argument
   4371 ** to sqlite3_update_hook().
   4372 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   4373 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   4374 ** to be invoked.
   4375 ** ^The third and fourth arguments to the callback contain pointers to the
   4376 ** database and table name containing the affected row.
   4377 ** ^The final callback parameter is the [rowid] of the row.
   4378 ** ^In the case of an update, this is the [rowid] after the update takes place.
   4379 **
   4380 ** ^(The update hook is not invoked when internal system tables are
   4381 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   4382 **
   4383 ** ^In the current implementation, the update hook
   4384 ** is not invoked when duplication rows are deleted because of an
   4385 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   4386 ** invoked when rows are deleted using the [truncate optimization].
   4387 ** The exceptions defined in this paragraph might change in a future
   4388 ** release of SQLite.
   4389 **
   4390 ** The update hook implementation must not do anything that will modify
   4391 ** the database connection that invoked the update hook.  Any actions
   4392 ** to modify the database connection must be deferred until after the
   4393 ** completion of the [sqlite3_step()] call that triggered the update hook.
   4394 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4395 ** database connections for the meaning of "modify" in this paragraph.
   4396 **
   4397 ** ^The sqlite3_update_hook(D,C,P) function
   4398 ** returns the P argument from the previous call
   4399 ** on the same [database connection] D, or NULL for
   4400 ** the first call on D.
   4401 **
   4402 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
   4403 ** interfaces.
   4404 */
   4405 SQLITE_API void *sqlite3_update_hook(
   4406   sqlite3*,
   4407   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   4408   void*
   4409 );
   4410 
   4411 /*
   4412 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   4413 ** KEYWORDS: {shared cache}
   4414 **
   4415 ** ^(This routine enables or disables the sharing of the database cache
   4416 ** and schema data structures between [database connection | connections]
   4417 ** to the same database. Sharing is enabled if the argument is true
   4418 ** and disabled if the argument is false.)^
   4419 **
   4420 ** ^Cache sharing is enabled and disabled for an entire process.
   4421 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
   4422 ** sharing was enabled or disabled for each thread separately.
   4423 **
   4424 ** ^(The cache sharing mode set by this interface effects all subsequent
   4425 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   4426 ** Existing database connections continue use the sharing mode
   4427 ** that was in effect at the time they were opened.)^
   4428 **
   4429 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   4430 ** successfully.  An [error code] is returned otherwise.)^
   4431 **
   4432 ** ^Shared cache is disabled by default. But this might change in
   4433 ** future releases of SQLite.  Applications that care about shared
   4434 ** cache setting should set it explicitly.
   4435 **
   4436 ** See Also:  [SQLite Shared-Cache Mode]
   4437 */
   4438 SQLITE_API int sqlite3_enable_shared_cache(int);
   4439 
   4440 /*
   4441 ** CAPI3REF: Attempt To Free Heap Memory
   4442 **
   4443 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   4444 ** of heap memory by deallocating non-essential memory allocations
   4445 ** held by the database library.   Memory used to cache database
   4446 ** pages to improve performance is an example of non-essential memory.
   4447 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   4448 ** which might be more or less than the amount requested.
   4449 */
   4450 SQLITE_API int sqlite3_release_memory(int);
   4451 
   4452 /*
   4453 ** CAPI3REF: Impose A Limit On Heap Size
   4454 **
   4455 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
   4456 ** on the amount of heap memory that may be allocated by SQLite.
   4457 ** ^If an internal allocation is requested that would exceed the
   4458 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
   4459 ** more times to free up some space before the allocation is performed.
   4460 **
   4461 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
   4462 ** cannot free sufficient memory to prevent the limit from being exceeded,
   4463 ** the memory is allocated anyway and the current operation proceeds.
   4464 **
   4465 ** ^A negative or zero value for N means that there is no soft heap limit and
   4466 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
   4467 ** ^The default value for the soft heap limit is zero.
   4468 **
   4469 ** ^(SQLite makes a best effort to honor the soft heap limit.
   4470 ** But if the soft heap limit cannot be honored, execution will
   4471 ** continue without error or notification.)^  This is why the limit is
   4472 ** called a "soft" limit.  It is advisory only.
   4473 **
   4474 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
   4475 ** allocated by a single thread - the same thread in which this routine
   4476 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
   4477 ** applied to all threads. The value specified for the soft heap limit
   4478 ** is an upper bound on the total memory allocation for all threads. In
   4479 ** version 3.5.0 there is no mechanism for limiting the heap usage for
   4480 ** individual threads.
   4481 */
   4482 SQLITE_API void sqlite3_soft_heap_limit(int);
   4483 
   4484 /*
   4485 ** CAPI3REF: Extract Metadata About A Column Of A Table
   4486 **
   4487 ** ^This routine returns metadata about a specific column of a specific
   4488 ** database table accessible using the [database connection] handle
   4489 ** passed as the first function argument.
   4490 **
   4491 ** ^The column is identified by the second, third and fourth parameters to
   4492 ** this function. ^The second parameter is either the name of the database
   4493 ** (i.e. "main", "temp", or an attached database) containing the specified
   4494 ** table or NULL. ^If it is NULL, then all attached databases are searched
   4495 ** for the table using the same algorithm used by the database engine to
   4496 ** resolve unqualified table references.
   4497 **
   4498 ** ^The third and fourth parameters to this function are the table and column
   4499 ** name of the desired column, respectively. Neither of these parameters
   4500 ** may be NULL.
   4501 **
   4502 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   4503 ** and subsequent parameters to this function. ^Any of these arguments may be
   4504 ** NULL, in which case the corresponding element of metadata is omitted.
   4505 **
   4506 ** ^(<blockquote>
   4507 ** <table border="1">
   4508 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   4509 **
   4510 ** <tr><td> 5th <td> const char* <td> Data type
   4511 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   4512 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   4513 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   4514 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   4515 ** </table>
   4516 ** </blockquote>)^
   4517 **
   4518 ** ^The memory pointed to by the character pointers returned for the
   4519 ** declaration type and collation sequence is valid only until the next
   4520 ** call to any SQLite API function.
   4521 **
   4522 ** ^If the specified table is actually a view, an [error code] is returned.
   4523 **
   4524 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
   4525 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   4526 ** parameters are set for the explicitly declared column. ^(If there is no
   4527 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
   4528 ** parameters are set as follows:
   4529 **
   4530 ** <pre>
   4531 **     data type: "INTEGER"
   4532 **     collation sequence: "BINARY"
   4533 **     not null: 0
   4534 **     primary key: 1
   4535 **     auto increment: 0
   4536 ** </pre>)^
   4537 **
   4538 ** ^(This function may load one or more schemas from database files. If an
   4539 ** error occurs during this process, or if the requested table or column
   4540 ** cannot be found, an [error code] is returned and an error message left
   4541 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
   4542 **
   4543 ** ^This API is only available if the library was compiled with the
   4544 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
   4545 */
   4546 SQLITE_API int sqlite3_table_column_metadata(
   4547   sqlite3 *db,                /* Connection handle */
   4548   const char *zDbName,        /* Database name or NULL */
   4549   const char *zTableName,     /* Table name */
   4550   const char *zColumnName,    /* Column name */
   4551   char const **pzDataType,    /* OUTPUT: Declared data type */
   4552   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   4553   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   4554   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   4555   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   4556 );
   4557 
   4558 /*
   4559 ** CAPI3REF: Load An Extension
   4560 **
   4561 ** ^This interface loads an SQLite extension library from the named file.
   4562 **
   4563 ** ^The sqlite3_load_extension() interface attempts to load an
   4564 ** SQLite extension library contained in the file zFile.
   4565 **
   4566 ** ^The entry point is zProc.
   4567 ** ^zProc may be 0, in which case the name of the entry point
   4568 ** defaults to "sqlite3_extension_init".
   4569 ** ^The sqlite3_load_extension() interface returns
   4570 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   4571 ** ^If an error occurs and pzErrMsg is not 0, then the
   4572 ** [sqlite3_load_extension()] interface shall attempt to
   4573 ** fill *pzErrMsg with error message text stored in memory
   4574 ** obtained from [sqlite3_malloc()]. The calling function
   4575 ** should free this memory by calling [sqlite3_free()].
   4576 **
   4577 ** ^Extension loading must be enabled using
   4578 ** [sqlite3_enable_load_extension()] prior to calling this API,
   4579 ** otherwise an error will be returned.
   4580 **
   4581 ** See also the [load_extension() SQL function].
   4582 */
   4583 SQLITE_API int sqlite3_load_extension(
   4584   sqlite3 *db,          /* Load the extension into this database connection */
   4585   const char *zFile,    /* Name of the shared library containing extension */
   4586   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   4587   char **pzErrMsg       /* Put error message here if not 0 */
   4588 );
   4589 
   4590 /*
   4591 ** CAPI3REF: Enable Or Disable Extension Loading
   4592 **
   4593 ** ^So as not to open security holes in older applications that are
   4594 ** unprepared to deal with extension loading, and as a means of disabling
   4595 ** extension loading while evaluating user-entered SQL, the following API
   4596 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   4597 **
   4598 ** ^Extension loading is off by default. See ticket #1863.
   4599 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   4600 ** to turn extension loading on and call it with onoff==0 to turn
   4601 ** it back off again.
   4602 */
   4603 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   4604 
   4605 /*
   4606 ** CAPI3REF: Automatically Load An Extensions
   4607 **
   4608 ** ^This API can be invoked at program startup in order to register
   4609 ** one or more statically linked extensions that will be available
   4610 ** to all new [database connections].
   4611 **
   4612 ** ^(This routine stores a pointer to the extension entry point
   4613 ** in an array that is obtained from [sqlite3_malloc()].  That memory
   4614 ** is deallocated by [sqlite3_reset_auto_extension()].)^
   4615 **
   4616 ** ^This function registers an extension entry point that is
   4617 ** automatically invoked whenever a new [database connection]
   4618 ** is opened using [sqlite3_open()], [sqlite3_open16()],
   4619 ** or [sqlite3_open_v2()].
   4620 ** ^Duplicate extensions are detected so calling this routine
   4621 ** multiple times with the same extension is harmless.
   4622 ** ^Automatic extensions apply across all threads.
   4623 */
   4624 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
   4625 
   4626 /*
   4627 ** CAPI3REF: Reset Automatic Extension Loading
   4628 **
   4629 ** ^(This function disables all previously registered automatic
   4630 ** extensions. It undoes the effect of all prior
   4631 ** [sqlite3_auto_extension()] calls.)^
   4632 **
   4633 ** ^This function disables automatic extensions in all threads.
   4634 */
   4635 SQLITE_API void sqlite3_reset_auto_extension(void);
   4636 
   4637 /*
   4638 ****** EXPERIMENTAL - subject to change without notice **************
   4639 **
   4640 ** The interface to the virtual-table mechanism is currently considered
   4641 ** to be experimental.  The interface might change in incompatible ways.
   4642 ** If this is a problem for you, do not use the interface at this time.
   4643 **
   4644 ** When the virtual-table mechanism stabilizes, we will declare the
   4645 ** interface fixed, support it indefinitely, and remove this comment.
   4646 */
   4647 
   4648 /*
   4649 ** Structures used by the virtual table interface
   4650 */
   4651 typedef struct sqlite3_vtab sqlite3_vtab;
   4652 typedef struct sqlite3_index_info sqlite3_index_info;
   4653 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   4654 typedef struct sqlite3_module sqlite3_module;
   4655 
   4656 /*
   4657 ** CAPI3REF: Virtual Table Object
   4658 ** KEYWORDS: sqlite3_module {virtual table module}
   4659 ** EXPERIMENTAL
   4660 **
   4661 ** This structure, sometimes called a a "virtual table module",
   4662 ** defines the implementation of a [virtual tables].
   4663 ** This structure consists mostly of methods for the module.
   4664 **
   4665 ** ^A virtual table module is created by filling in a persistent
   4666 ** instance of this structure and passing a pointer to that instance
   4667 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   4668 ** ^The registration remains valid until it is replaced by a different
   4669 ** module or until the [database connection] closes.  The content
   4670 ** of this structure must not change while it is registered with
   4671 ** any database connection.
   4672 */
   4673 struct sqlite3_module {
   4674   int iVersion;
   4675   int (*xCreate)(sqlite3*, void *pAux,
   4676                int argc, const char *const*argv,
   4677                sqlite3_vtab **ppVTab, char**);
   4678   int (*xConnect)(sqlite3*, void *pAux,
   4679                int argc, const char *const*argv,
   4680                sqlite3_vtab **ppVTab, char**);
   4681   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   4682   int (*xDisconnect)(sqlite3_vtab *pVTab);
   4683   int (*xDestroy)(sqlite3_vtab *pVTab);
   4684   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   4685   int (*xClose)(sqlite3_vtab_cursor*);
   4686   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   4687                 int argc, sqlite3_value **argv);
   4688   int (*xNext)(sqlite3_vtab_cursor*);
   4689   int (*xEof)(sqlite3_vtab_cursor*);
   4690   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   4691   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   4692   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   4693   int (*xBegin)(sqlite3_vtab *pVTab);
   4694   int (*xSync)(sqlite3_vtab *pVTab);
   4695   int (*xCommit)(sqlite3_vtab *pVTab);
   4696   int (*xRollback)(sqlite3_vtab *pVTab);
   4697   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   4698                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   4699                        void **ppArg);
   4700   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   4701 };
   4702 
   4703 /*
   4704 ** CAPI3REF: Virtual Table Indexing Information
   4705 ** KEYWORDS: sqlite3_index_info
   4706 ** EXPERIMENTAL
   4707 **
   4708 ** The sqlite3_index_info structure and its substructures is used to
   4709 ** pass information into and receive the reply from the [xBestIndex]
   4710 ** method of a [virtual table module].  The fields under **Inputs** are the
   4711 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   4712 ** results into the **Outputs** fields.
   4713 **
   4714 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   4715 **
   4716 ** <pre>column OP expr</pre>
   4717 **
   4718 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   4719 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
   4720 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   4721 ** expr on the right-hand side can be evaluated (and thus the constraint
   4722 ** is usable) and false if it cannot.)^
   4723 **
   4724 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   4725 ** and makes other simplifications to the WHERE clause in an attempt to
   4726 ** get as many WHERE clause terms into the form shown above as possible.
   4727 ** ^The aConstraint[] array only reports WHERE clause terms that are
   4728 ** relevant to the particular virtual table being queried.
   4729 **
   4730 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   4731 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   4732 **
   4733 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   4734 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   4735 ** the right-hand side of the corresponding aConstraint[] is evaluated
   4736 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   4737 ** is true, then the constraint is assumed to be fully handled by the
   4738 ** virtual table and is not checked again by SQLite.)^
   4739 **
   4740 ** ^The idxNum and idxPtr values are recorded and passed into the
   4741 ** [xFilter] method.
   4742 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   4743 ** needToFreeIdxPtr is true.
   4744 **
   4745 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   4746 ** the correct order to satisfy the ORDER BY clause so that no separate
   4747 ** sorting step is required.
   4748 **
   4749 ** ^The estimatedCost value is an estimate of the cost of doing the
   4750 ** particular lookup.  A full scan of a table with N entries should have
   4751 ** a cost of N.  A binary search of a table of N entries should have a
   4752 ** cost of approximately log(N).
   4753 */
   4754 struct sqlite3_index_info {
   4755   /* Inputs */
   4756   int nConstraint;           /* Number of entries in aConstraint */
   4757   struct sqlite3_index_constraint {
   4758      int iColumn;              /* Column on left-hand side of constraint */
   4759      unsigned char op;         /* Constraint operator */
   4760      unsigned char usable;     /* True if this constraint is usable */
   4761      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   4762   } *aConstraint;            /* Table of WHERE clause constraints */
   4763   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   4764   struct sqlite3_index_orderby {
   4765      int iColumn;              /* Column number */
   4766      unsigned char desc;       /* True for DESC.  False for ASC. */
   4767   } *aOrderBy;               /* The ORDER BY clause */
   4768   /* Outputs */
   4769   struct sqlite3_index_constraint_usage {
   4770     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   4771     unsigned char omit;      /* Do not code a test for this constraint */
   4772   } *aConstraintUsage;
   4773   int idxNum;                /* Number used to identify the index */
   4774   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   4775   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   4776   int orderByConsumed;       /* True if output is already ordered */
   4777   double estimatedCost;      /* Estimated cost of using this index */
   4778 };
   4779 #define SQLITE_INDEX_CONSTRAINT_EQ    2
   4780 #define SQLITE_INDEX_CONSTRAINT_GT    4
   4781 #define SQLITE_INDEX_CONSTRAINT_LE    8
   4782 #define SQLITE_INDEX_CONSTRAINT_LT    16
   4783 #define SQLITE_INDEX_CONSTRAINT_GE    32
   4784 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
   4785 
   4786 /*
   4787 ** CAPI3REF: Register A Virtual Table Implementation
   4788 ** EXPERIMENTAL
   4789 **
   4790 ** ^These routines are used to register a new [virtual table module] name.
   4791 ** ^Module names must be registered before
   4792 ** creating a new [virtual table] using the module and before using a
   4793 ** preexisting [virtual table] for the module.
   4794 **
   4795 ** ^The module name is registered on the [database connection] specified
   4796 ** by the first parameter.  ^The name of the module is given by the
   4797 ** second parameter.  ^The third parameter is a pointer to
   4798 ** the implementation of the [virtual table module].   ^The fourth
   4799 ** parameter is an arbitrary client data pointer that is passed through
   4800 ** into the [xCreate] and [xConnect] methods of the virtual table module
   4801 ** when a new virtual table is be being created or reinitialized.
   4802 **
   4803 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   4804 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   4805 ** invoke the destructor function (if it is not NULL) when SQLite
   4806 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
   4807 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   4808 ** destructor.
   4809 */
   4810 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
   4811   sqlite3 *db,               /* SQLite connection to register module with */
   4812   const char *zName,         /* Name of the module */
   4813   const sqlite3_module *p,   /* Methods for the module */
   4814   void *pClientData          /* Client data for xCreate/xConnect */
   4815 );
   4816 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
   4817   sqlite3 *db,               /* SQLite connection to register module with */
   4818   const char *zName,         /* Name of the module */
   4819   const sqlite3_module *p,   /* Methods for the module */
   4820   void *pClientData,         /* Client data for xCreate/xConnect */
   4821   void(*xDestroy)(void*)     /* Module destructor function */
   4822 );
   4823 
   4824 /*
   4825 ** CAPI3REF: Virtual Table Instance Object
   4826 ** KEYWORDS: sqlite3_vtab
   4827 ** EXPERIMENTAL
   4828 **
   4829 ** Every [virtual table module] implementation uses a subclass
   4830 ** of this object to describe a particular instance
   4831 ** of the [virtual table].  Each subclass will
   4832 ** be tailored to the specific needs of the module implementation.
   4833 ** The purpose of this superclass is to define certain fields that are
   4834 ** common to all module implementations.
   4835 **
   4836 ** ^Virtual tables methods can set an error message by assigning a
   4837 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   4838 ** take care that any prior string is freed by a call to [sqlite3_free()]
   4839 ** prior to assigning a new string to zErrMsg.  ^After the error message
   4840 ** is delivered up to the client application, the string will be automatically
   4841 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   4842 */
   4843 struct sqlite3_vtab {
   4844   const sqlite3_module *pModule;  /* The module for this virtual table */
   4845   int nRef;                       /* NO LONGER USED */
   4846   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   4847   /* Virtual table implementations will typically add additional fields */
   4848 };
   4849 
   4850 /*
   4851 ** CAPI3REF: Virtual Table Cursor Object
   4852 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   4853 ** EXPERIMENTAL
   4854 **
   4855 ** Every [virtual table module] implementation uses a subclass of the
   4856 ** following structure to describe cursors that point into the
   4857 ** [virtual table] and are used
   4858 ** to loop through the virtual table.  Cursors are created using the
   4859 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   4860 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   4861 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   4862 ** of the module.  Each module implementation will define
   4863 ** the content of a cursor structure to suit its own needs.
   4864 **
   4865 ** This superclass exists in order to define fields of the cursor that
   4866 ** are common to all implementations.
   4867 */
   4868 struct sqlite3_vtab_cursor {
   4869   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   4870   /* Virtual table implementations will typically add additional fields */
   4871 };
   4872 
   4873 /*
   4874 ** CAPI3REF: Declare The Schema Of A Virtual Table
   4875 ** EXPERIMENTAL
   4876 **
   4877 ** ^The [xCreate] and [xConnect] methods of a
   4878 ** [virtual table module] call this interface
   4879 ** to declare the format (the names and datatypes of the columns) of
   4880 ** the virtual tables they implement.
   4881 */
   4882 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   4883 
   4884 /*
   4885 ** CAPI3REF: Overload A Function For A Virtual Table
   4886 ** EXPERIMENTAL
   4887 **
   4888 ** ^(Virtual tables can provide alternative implementations of functions
   4889 ** using the [xFindFunction] method of the [virtual table module].
   4890 ** But global versions of those functions
   4891 ** must exist in order to be overloaded.)^
   4892 **
   4893 ** ^(This API makes sure a global version of a function with a particular
   4894 ** name and number of parameters exists.  If no such function exists
   4895 ** before this API is called, a new function is created.)^  ^The implementation
   4896 ** of the new function always causes an exception to be thrown.  So
   4897 ** the new function is not good for anything by itself.  Its only
   4898 ** purpose is to be a placeholder function that can be overloaded
   4899 ** by a [virtual table].
   4900 */
   4901 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   4902 
   4903 /*
   4904 ** The interface to the virtual-table mechanism defined above (back up
   4905 ** to a comment remarkably similar to this one) is currently considered
   4906 ** to be experimental.  The interface might change in incompatible ways.
   4907 ** If this is a problem for you, do not use the interface at this time.
   4908 **
   4909 ** When the virtual-table mechanism stabilizes, we will declare the
   4910 ** interface fixed, support it indefinitely, and remove this comment.
   4911 **
   4912 ****** EXPERIMENTAL - subject to change without notice **************
   4913 */
   4914 
   4915 /*
   4916 ** CAPI3REF: A Handle To An Open BLOB
   4917 ** KEYWORDS: {BLOB handle} {BLOB handles}
   4918 **
   4919 ** An instance of this object represents an open BLOB on which
   4920 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   4921 ** ^Objects of this type are created by [sqlite3_blob_open()]
   4922 ** and destroyed by [sqlite3_blob_close()].
   4923 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   4924 ** can be used to read or write small subsections of the BLOB.
   4925 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   4926 */
   4927 typedef struct sqlite3_blob sqlite3_blob;
   4928 
   4929 /*
   4930 ** CAPI3REF: Open A BLOB For Incremental I/O
   4931 **
   4932 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   4933 ** in row iRow, column zColumn, table zTable in database zDb;
   4934 ** in other words, the same BLOB that would be selected by:
   4935 **
   4936 ** <pre>
   4937 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   4938 ** </pre>)^
   4939 **
   4940 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   4941 ** and write access. ^If it is zero, the BLOB is opened for read access.
   4942 ** ^It is not possible to open a column that is part of an index or primary
   4943 ** key for writing. ^If [foreign key constraints] are enabled, it is
   4944 ** not possible to open a column that is part of a [child key] for writing.
   4945 **
   4946 ** ^Note that the database name is not the filename that contains
   4947 ** the database but rather the symbolic name of the database that
   4948 ** appears after the AS keyword when the database is connected using [ATTACH].
   4949 ** ^For the main database file, the database name is "main".
   4950 ** ^For TEMP tables, the database name is "temp".
   4951 **
   4952 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
   4953 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
   4954 ** to be a null pointer.)^
   4955 ** ^This function sets the [database connection] error code and message
   4956 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
   4957 ** functions. ^Note that the *ppBlob variable is always initialized in a
   4958 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
   4959 ** regardless of the success or failure of this routine.
   4960 **
   4961 ** ^(If the row that a BLOB handle points to is modified by an
   4962 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   4963 ** then the BLOB handle is marked as "expired".
   4964 ** This is true if any column of the row is changed, even a column
   4965 ** other than the one the BLOB handle is open on.)^
   4966 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   4967 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
   4968 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   4969 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   4970 ** commit if the transaction continues to completion.)^
   4971 **
   4972 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   4973 ** the opened blob.  ^The size of a blob may not be changed by this
   4974 ** interface.  Use the [UPDATE] SQL command to change the size of a
   4975 ** blob.
   4976 **
   4977 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   4978 ** and the built-in [zeroblob] SQL function can be used, if desired,
   4979 ** to create an empty, zero-filled blob in which to read or write using
   4980 ** this interface.
   4981 **
   4982 ** To avoid a resource leak, every open [BLOB handle] should eventually
   4983 ** be released by a call to [sqlite3_blob_close()].
   4984 */
   4985 SQLITE_API int sqlite3_blob_open(
   4986   sqlite3*,
   4987   const char *zDb,
   4988   const char *zTable,
   4989   const char *zColumn,
   4990   sqlite3_int64 iRow,
   4991   int flags,
   4992   sqlite3_blob **ppBlob
   4993 );
   4994 
   4995 /*
   4996 ** CAPI3REF: Close A BLOB Handle
   4997 **
   4998 ** ^Closes an open [BLOB handle].
   4999 **
   5000 ** ^Closing a BLOB shall cause the current transaction to commit
   5001 ** if there are no other BLOBs, no pending prepared statements, and the
   5002 ** database connection is in [autocommit mode].
   5003 ** ^If any writes were made to the BLOB, they might be held in cache
   5004 ** until the close operation if they will fit.
   5005 **
   5006 ** ^(Closing the BLOB often forces the changes
   5007 ** out to disk and so if any I/O errors occur, they will likely occur
   5008 ** at the time when the BLOB is closed.  Any errors that occur during
   5009 ** closing are reported as a non-zero return value.)^
   5010 **
   5011 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
   5012 ** an error code, the BLOB is still closed.)^
   5013 **
   5014 ** ^Calling this routine with a null pointer (such as would be returned
   5015 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
   5016 */
   5017 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   5018 
   5019 /*
   5020 ** CAPI3REF: Return The Size Of An Open BLOB
   5021 **
   5022 ** ^Returns the size in bytes of the BLOB accessible via the
   5023 ** successfully opened [BLOB handle] in its only argument.  ^The
   5024 ** incremental blob I/O routines can only read or overwriting existing
   5025 ** blob content; they cannot change the size of a blob.
   5026 **
   5027 ** This routine only works on a [BLOB handle] which has been created
   5028 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5029 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5030 ** to this routine results in undefined and probably undesirable behavior.
   5031 */
   5032 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   5033 
   5034 /*
   5035 ** CAPI3REF: Read Data From A BLOB Incrementally
   5036 **
   5037 ** ^(This function is used to read data from an open [BLOB handle] into a
   5038 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   5039 ** from the open BLOB, starting at offset iOffset.)^
   5040 **
   5041 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5042 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   5043 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   5044 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   5045 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5046 **
   5047 ** ^An attempt to read from an expired [BLOB handle] fails with an
   5048 ** error code of [SQLITE_ABORT].
   5049 **
   5050 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   5051 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   5052 **
   5053 ** This routine only works on a [BLOB handle] which has been created
   5054 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5055 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5056 ** to this routine results in undefined and probably undesirable behavior.
   5057 **
   5058 ** See also: [sqlite3_blob_write()].
   5059 */
   5060 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   5061 
   5062 /*
   5063 ** CAPI3REF: Write Data Into A BLOB Incrementally
   5064 **
   5065 ** ^This function is used to write data into an open [BLOB handle] from a
   5066 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
   5067 ** into the open BLOB, starting at offset iOffset.
   5068 **
   5069 ** ^If the [BLOB handle] passed as the first argument was not opened for
   5070 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   5071 ** this function returns [SQLITE_READONLY].
   5072 **
   5073 ** ^This function may only modify the contents of the BLOB; it is
   5074 ** not possible to increase the size of a BLOB using this API.
   5075 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5076 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
   5077 ** less than zero [SQLITE_ERROR] is returned and no data is written.
   5078 ** The size of the BLOB (and hence the maximum value of N+iOffset)
   5079 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5080 **
   5081 ** ^An attempt to write to an expired [BLOB handle] fails with an
   5082 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   5083 ** before the [BLOB handle] expired are not rolled back by the
   5084 ** expiration of the handle, though of course those changes might
   5085 ** have been overwritten by the statement that expired the BLOB handle
   5086 ** or by other independent statements.
   5087 **
   5088 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   5089 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   5090 **
   5091 ** This routine only works on a [BLOB handle] which has been created
   5092 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5093 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5094 ** to this routine results in undefined and probably undesirable behavior.
   5095 **
   5096 ** See also: [sqlite3_blob_read()].
   5097 */
   5098 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   5099 
   5100 /*
   5101 ** CAPI3REF: Virtual File System Objects
   5102 **
   5103 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   5104 ** that SQLite uses to interact
   5105 ** with the underlying operating system.  Most SQLite builds come with a
   5106 ** single default VFS that is appropriate for the host computer.
   5107 ** New VFSes can be registered and existing VFSes can be unregistered.
   5108 ** The following interfaces are provided.
   5109 **
   5110 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   5111 ** ^Names are case sensitive.
   5112 ** ^Names are zero-terminated UTF-8 strings.
   5113 ** ^If there is no match, a NULL pointer is returned.
   5114 ** ^If zVfsName is NULL then the default VFS is returned.
   5115 **
   5116 ** ^New VFSes are registered with sqlite3_vfs_register().
   5117 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   5118 ** ^The same VFS can be registered multiple times without injury.
   5119 ** ^To make an existing VFS into the default VFS, register it again
   5120 ** with the makeDflt flag set.  If two different VFSes with the
   5121 ** same name are registered, the behavior is undefined.  If a
   5122 ** VFS is registered with a name that is NULL or an empty string,
   5123 ** then the behavior is undefined.
   5124 **
   5125 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   5126 ** ^(If the default VFS is unregistered, another VFS is chosen as
   5127 ** the default.  The choice for the new VFS is arbitrary.)^
   5128 */
   5129 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   5130 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   5131 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   5132 
   5133 /*
   5134 ** CAPI3REF: Mutexes
   5135 **
   5136 ** The SQLite core uses these routines for thread
   5137 ** synchronization. Though they are intended for internal
   5138 ** use by SQLite, code that links against SQLite is
   5139 ** permitted to use any of these routines.
   5140 **
   5141 ** The SQLite source code contains multiple implementations
   5142 ** of these mutex routines.  An appropriate implementation
   5143 ** is selected automatically at compile-time.  ^(The following
   5144 ** implementations are available in the SQLite core:
   5145 **
   5146 ** <ul>
   5147 ** <li>   SQLITE_MUTEX_OS2
   5148 ** <li>   SQLITE_MUTEX_PTHREAD
   5149 ** <li>   SQLITE_MUTEX_W32
   5150 ** <li>   SQLITE_MUTEX_NOOP
   5151 ** </ul>)^
   5152 **
   5153 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
   5154 ** that does no real locking and is appropriate for use in
   5155 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
   5156 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
   5157 ** are appropriate for use on OS/2, Unix, and Windows.
   5158 **
   5159 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   5160 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   5161 ** implementation is included with the library. In this case the
   5162 ** application must supply a custom mutex implementation using the
   5163 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   5164 ** before calling sqlite3_initialize() or any other public sqlite3_
   5165 ** function that calls sqlite3_initialize().)^
   5166 **
   5167 ** ^The sqlite3_mutex_alloc() routine allocates a new
   5168 ** mutex and returns a pointer to it. ^If it returns NULL
   5169 ** that means that a mutex could not be allocated.  ^SQLite
   5170 ** will unwind its stack and return an error.  ^(The argument
   5171 ** to sqlite3_mutex_alloc() is one of these integer constants:
   5172 **
   5173 ** <ul>
   5174 ** <li>  SQLITE_MUTEX_FAST
   5175 ** <li>  SQLITE_MUTEX_RECURSIVE
   5176 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   5177 ** <li>  SQLITE_MUTEX_STATIC_MEM
   5178 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   5179 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   5180 ** <li>  SQLITE_MUTEX_STATIC_LRU
   5181 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   5182 ** </ul>)^
   5183 **
   5184 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   5185 ** cause sqlite3_mutex_alloc() to create
   5186 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   5187 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   5188 ** The mutex implementation does not need to make a distinction
   5189 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   5190 ** not want to.  ^SQLite will only request a recursive mutex in
   5191 ** cases where it really needs one.  ^If a faster non-recursive mutex
   5192 ** implementation is available on the host platform, the mutex subsystem
   5193 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   5194 **
   5195 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   5196 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   5197 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
   5198 ** used by the current version of SQLite.  Future versions of SQLite
   5199 ** may add additional static mutexes.  Static mutexes are for internal
   5200 ** use by SQLite only.  Applications that use SQLite mutexes should
   5201 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   5202 ** SQLITE_MUTEX_RECURSIVE.
   5203 **
   5204 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   5205 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   5206 ** returns a different mutex on every call.  ^But for the static
   5207 ** mutex types, the same mutex is returned on every call that has
   5208 ** the same type number.
   5209 **
   5210 ** ^The sqlite3_mutex_free() routine deallocates a previously
   5211 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
   5212 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
   5213 ** use when they are deallocated.  Attempting to deallocate a static
   5214 ** mutex results in undefined behavior.  ^SQLite never deallocates
   5215 ** a static mutex.
   5216 **
   5217 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   5218 ** to enter a mutex.  ^If another thread is already within the mutex,
   5219 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   5220 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   5221 ** upon successful entry.  ^(Mutexes created using
   5222 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   5223 ** In such cases the,
   5224 ** mutex must be exited an equal number of times before another thread
   5225 ** can enter.)^  ^(If the same thread tries to enter any other
   5226 ** kind of mutex more than once, the behavior is undefined.
   5227 ** SQLite will never exhibit
   5228 ** such behavior in its own use of mutexes.)^
   5229 **
   5230 ** ^(Some systems (for example, Windows 95) do not support the operation
   5231 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   5232 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
   5233 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
   5234 **
   5235 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   5236 ** previously entered by the same thread.   ^(The behavior
   5237 ** is undefined if the mutex is not currently entered by the
   5238 ** calling thread or is not currently allocated.  SQLite will
   5239 ** never do either.)^
   5240 **
   5241 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   5242 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   5243 ** behave as no-ops.
   5244 **
   5245 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   5246 */
   5247 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   5248 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   5249 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   5250 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   5251 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   5252 
   5253 /*
   5254 ** CAPI3REF: Mutex Methods Object
   5255 ** EXPERIMENTAL
   5256 **
   5257 ** An instance of this structure defines the low-level routines
   5258 ** used to allocate and use mutexes.
   5259 **
   5260 ** Usually, the default mutex implementations provided by SQLite are
   5261 ** sufficient, however the user has the option of substituting a custom
   5262 ** implementation for specialized deployments or systems for which SQLite
   5263 ** does not provide a suitable implementation. In this case, the user
   5264 ** creates and populates an instance of this structure to pass
   5265 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   5266 ** Additionally, an instance of this structure can be used as an
   5267 ** output variable when querying the system for the current mutex
   5268 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   5269 **
   5270 ** ^The xMutexInit method defined by this structure is invoked as
   5271 ** part of system initialization by the sqlite3_initialize() function.
   5272 ** ^The xMutexInit routine is calle by SQLite exactly once for each
   5273 ** effective call to [sqlite3_initialize()].
   5274 **
   5275 ** ^The xMutexEnd method defined by this structure is invoked as
   5276 ** part of system shutdown by the sqlite3_shutdown() function. The
   5277 ** implementation of this method is expected to release all outstanding
   5278 ** resources obtained by the mutex methods implementation, especially
   5279 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   5280 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   5281 **
   5282 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   5283 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   5284 ** xMutexNotheld) implement the following interfaces (respectively):
   5285 **
   5286 ** <ul>
   5287 **   <li>  [sqlite3_mutex_alloc()] </li>
   5288 **   <li>  [sqlite3_mutex_free()] </li>
   5289 **   <li>  [sqlite3_mutex_enter()] </li>
   5290 **   <li>  [sqlite3_mutex_try()] </li>
   5291 **   <li>  [sqlite3_mutex_leave()] </li>
   5292 **   <li>  [sqlite3_mutex_held()] </li>
   5293 **   <li>  [sqlite3_mutex_notheld()] </li>
   5294 ** </ul>)^
   5295 **
   5296 ** The only difference is that the public sqlite3_XXX functions enumerated
   5297 ** above silently ignore any invocations that pass a NULL pointer instead
   5298 ** of a valid mutex handle. The implementations of the methods defined
   5299 ** by this structure are not required to handle this case, the results
   5300 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   5301 ** (i.e. it is acceptable to provide an implementation that segfaults if
   5302 ** it is passed a NULL pointer).
   5303 **
   5304 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
   5305 ** invoke xMutexInit() mutiple times within the same process and without
   5306 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   5307 ** xMutexInit() must be no-ops.
   5308 **
   5309 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   5310 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
   5311 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   5312 ** memory allocation for a fast or recursive mutex.
   5313 **
   5314 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   5315 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   5316 ** If xMutexInit fails in any way, it is expected to clean up after itself
   5317 ** prior to returning.
   5318 */
   5319 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   5320 struct sqlite3_mutex_methods {
   5321   int (*xMutexInit)(void);
   5322   int (*xMutexEnd)(void);
   5323   sqlite3_mutex *(*xMutexAlloc)(int);
   5324   void (*xMutexFree)(sqlite3_mutex *);
   5325   void (*xMutexEnter)(sqlite3_mutex *);
   5326   int (*xMutexTry)(sqlite3_mutex *);
   5327   void (*xMutexLeave)(sqlite3_mutex *);
   5328   int (*xMutexHeld)(sqlite3_mutex *);
   5329   int (*xMutexNotheld)(sqlite3_mutex *);
   5330 };
   5331 
   5332 /*
   5333 ** CAPI3REF: Mutex Verification Routines
   5334 **
   5335 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   5336 ** are intended for use inside assert() statements.  ^The SQLite core
   5337 ** never uses these routines except inside an assert() and applications
   5338 ** are advised to follow the lead of the core.  ^The SQLite core only
   5339 ** provides implementations for these routines when it is compiled
   5340 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
   5341 ** are only required to provide these routines if SQLITE_DEBUG is
   5342 ** defined and if NDEBUG is not defined.
   5343 **
   5344 ** ^These routines should return true if the mutex in their argument
   5345 ** is held or not held, respectively, by the calling thread.
   5346 **
   5347 ** ^The implementation is not required to provided versions of these
   5348 ** routines that actually work. If the implementation does not provide working
   5349 ** versions of these routines, it should at least provide stubs that always
   5350 ** return true so that one does not get spurious assertion failures.
   5351 **
   5352 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
   5353 ** the routine should return 1.   This seems counter-intuitive since
   5354 ** clearly the mutex cannot be held if it does not exist.  But the
   5355 ** the reason the mutex does not exist is because the build is not
   5356 ** using mutexes.  And we do not want the assert() containing the
   5357 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   5358 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
   5359 ** interface should also return 1 when given a NULL pointer.
   5360 */
   5361 #ifndef NDEBUG
   5362 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   5363 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   5364 #endif
   5365 
   5366 /*
   5367 ** CAPI3REF: Mutex Types
   5368 **
   5369 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   5370 ** which is one of these integer constants.
   5371 **
   5372 ** The set of static mutexes may change from one SQLite release to the
   5373 ** next.  Applications that override the built-in mutex logic must be
   5374 ** prepared to accommodate additional static mutexes.
   5375 */
   5376 #define SQLITE_MUTEX_FAST             0
   5377 #define SQLITE_MUTEX_RECURSIVE        1
   5378 #define SQLITE_MUTEX_STATIC_MASTER    2
   5379 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   5380 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   5381 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   5382 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
   5383 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   5384 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
   5385 
   5386 /*
   5387 ** CAPI3REF: Retrieve the mutex for a database connection
   5388 **
   5389 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   5390 ** serializes access to the [database connection] given in the argument
   5391 ** when the [threading mode] is Serialized.
   5392 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   5393 ** routine returns a NULL pointer.
   5394 */
   5395 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   5396 
   5397 /*
   5398 ** CAPI3REF: Low-Level Control Of Database Files
   5399 **
   5400 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   5401 ** xFileControl method for the [sqlite3_io_methods] object associated
   5402 ** with a particular database identified by the second argument. ^The
   5403 ** name of the database "main" for the main database or "temp" for the
   5404 ** TEMP database, or the name that appears after the AS keyword for
   5405 ** databases that are added using the [ATTACH] SQL command.
   5406 ** ^A NULL pointer can be used in place of "main" to refer to the
   5407 ** main database file.
   5408 ** ^The third and fourth parameters to this routine
   5409 ** are passed directly through to the second and third parameters of
   5410 ** the xFileControl method.  ^The return value of the xFileControl
   5411 ** method becomes the return value of this routine.
   5412 **
   5413 ** ^If the second parameter (zDbName) does not match the name of any
   5414 ** open database file, then SQLITE_ERROR is returned.  ^This error
   5415 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   5416 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   5417 ** also return SQLITE_ERROR.  There is no way to distinguish between
   5418 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   5419 ** xFileControl method.
   5420 **
   5421 ** See also: [SQLITE_FCNTL_LOCKSTATE]
   5422 */
   5423 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   5424 
   5425 /*
   5426 ** CAPI3REF: Testing Interface
   5427 **
   5428 ** ^The sqlite3_test_control() interface is used to read out internal
   5429 ** state of SQLite and to inject faults into SQLite for testing
   5430 ** purposes.  ^The first parameter is an operation code that determines
   5431 ** the number, meaning, and operation of all subsequent parameters.
   5432 **
   5433 ** This interface is not for use by applications.  It exists solely
   5434 ** for verifying the correct operation of the SQLite library.  Depending
   5435 ** on how the SQLite library is compiled, this interface might not exist.
   5436 **
   5437 ** The details of the operation codes, their meanings, the parameters
   5438 ** they take, and what they do are all subject to change without notice.
   5439 ** Unlike most of the SQLite API, this function is not guaranteed to
   5440 ** operate consistently from one release to the next.
   5441 */
   5442 SQLITE_API int sqlite3_test_control(int op, ...);
   5443 
   5444 /*
   5445 ** CAPI3REF: Testing Interface Operation Codes
   5446 **
   5447 ** These constants are the valid operation code parameters used
   5448 ** as the first argument to [sqlite3_test_control()].
   5449 **
   5450 ** These parameters and their meanings are subject to change
   5451 ** without notice.  These values are for testing purposes only.
   5452 ** Applications should not use any of these parameters or the
   5453 ** [sqlite3_test_control()] interface.
   5454 */
   5455 #define SQLITE_TESTCTRL_FIRST                    5
   5456 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   5457 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   5458 #define SQLITE_TESTCTRL_PRNG_RESET               7
   5459 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   5460 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   5461 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   5462 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   5463 #define SQLITE_TESTCTRL_ASSERT                  12
   5464 #define SQLITE_TESTCTRL_ALWAYS                  13
   5465 #define SQLITE_TESTCTRL_RESERVE                 14
   5466 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   5467 #define SQLITE_TESTCTRL_ISKEYWORD               16
   5468 #define SQLITE_TESTCTRL_LAST                    16
   5469 
   5470 /*
   5471 ** CAPI3REF: SQLite Runtime Status
   5472 ** EXPERIMENTAL
   5473 **
   5474 ** ^This interface is used to retrieve runtime status information
   5475 ** about the preformance of SQLite, and optionally to reset various
   5476 ** highwater marks.  ^The first argument is an integer code for
   5477 ** the specific parameter to measure.  ^(Recognized integer codes
   5478 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
   5479 ** ^The current value of the parameter is returned into *pCurrent.
   5480 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   5481 ** resetFlag is true, then the highest record value is reset after
   5482 ** *pHighwater is written.  ^(Some parameters do not record the highest
   5483 ** value.  For those parameters
   5484 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   5485 ** ^(Other parameters record only the highwater mark and not the current
   5486 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   5487 **
   5488 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   5489 ** non-zero [error code] on failure.
   5490 **
   5491 ** This routine is threadsafe but is not atomic.  This routine can be
   5492 ** called while other threads are running the same or different SQLite
   5493 ** interfaces.  However the values returned in *pCurrent and
   5494 ** *pHighwater reflect the status of SQLite at different points in time
   5495 ** and it is possible that another thread might change the parameter
   5496 ** in between the times when *pCurrent and *pHighwater are written.
   5497 **
   5498 ** See also: [sqlite3_db_status()]
   5499 */
   5500 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   5501 
   5502 
   5503 /*
   5504 ** CAPI3REF: Status Parameters
   5505 ** EXPERIMENTAL
   5506 **
   5507 ** These integer constants designate various run-time status parameters
   5508 ** that can be returned by [sqlite3_status()].
   5509 **
   5510 ** <dl>
   5511 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   5512 ** <dd>This parameter is the current amount of memory checked out
   5513 ** using [sqlite3_malloc()], either directly or indirectly.  The
   5514 ** figure includes calls made to [sqlite3_malloc()] by the application
   5515 ** and internal memory usage by the SQLite library.  Scratch memory
   5516 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
   5517 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   5518 ** this parameter.  The amount returned is the sum of the allocation
   5519 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   5520 **
   5521 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   5522 ** <dd>This parameter records the largest memory allocation request
   5523 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   5524 ** internal equivalents).  Only the value returned in the
   5525 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5526 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5527 **
   5528 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   5529 ** <dd>This parameter returns the number of pages used out of the
   5530 ** [pagecache memory allocator] that was configured using
   5531 ** [SQLITE_CONFIG_PAGECACHE].  The
   5532 ** value returned is in pages, not in bytes.</dd>)^
   5533 **
   5534 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   5535 ** <dd>This parameter returns the number of bytes of page cache
   5536 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
   5537 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   5538 ** returned value includes allocations that overflowed because they
   5539 ** where too large (they were larger than the "sz" parameter to
   5540 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   5541 ** no space was left in the page cache.</dd>)^
   5542 **
   5543 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   5544 ** <dd>This parameter records the largest memory allocation request
   5545 ** handed to [pagecache memory allocator].  Only the value returned in the
   5546 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5547 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5548 **
   5549 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
   5550 ** <dd>This parameter returns the number of allocations used out of the
   5551 ** [scratch memory allocator] configured using
   5552 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
   5553 ** in bytes.  Since a single thread may only have one scratch allocation
   5554 ** outstanding at time, this parameter also reports the number of threads
   5555 ** using scratch memory at the same time.</dd>)^
   5556 **
   5557 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   5558 ** <dd>This parameter returns the number of bytes of scratch memory
   5559 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
   5560 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
   5561 ** returned include overflows because the requested allocation was too
   5562 ** larger (that is, because the requested allocation was larger than the
   5563 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
   5564 ** slots were available.
   5565 ** </dd>)^
   5566 **
   5567 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   5568 ** <dd>This parameter records the largest memory allocation request
   5569 ** handed to [scratch memory allocator].  Only the value returned in the
   5570 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5571 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5572 **
   5573 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   5574 ** <dd>This parameter records the deepest parser stack.  It is only
   5575 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   5576 ** </dl>
   5577 **
   5578 ** New status parameters may be added from time to time.
   5579 */
   5580 #define SQLITE_STATUS_MEMORY_USED          0
   5581 #define SQLITE_STATUS_PAGECACHE_USED       1
   5582 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   5583 #define SQLITE_STATUS_SCRATCH_USED         3
   5584 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
   5585 #define SQLITE_STATUS_MALLOC_SIZE          5
   5586 #define SQLITE_STATUS_PARSER_STACK         6
   5587 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   5588 #define SQLITE_STATUS_SCRATCH_SIZE         8
   5589 
   5590 /*
   5591 ** CAPI3REF: Database Connection Status
   5592 ** EXPERIMENTAL
   5593 **
   5594 ** ^This interface is used to retrieve runtime status information
   5595 ** about a single [database connection].  ^The first argument is the
   5596 ** database connection object to be interrogated.  ^The second argument
   5597 ** is the parameter to interrogate.  ^Currently, the only allowed value
   5598 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
   5599 ** Additional options will likely appear in future releases of SQLite.
   5600 **
   5601 ** ^The current value of the requested parameter is written into *pCur
   5602 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   5603 ** the resetFlg is true, then the highest instantaneous value is
   5604 ** reset back down to the current value.
   5605 **
   5606 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   5607 */
   5608 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   5609 
   5610 /*
   5611 ** CAPI3REF: Status Parameters for database connections
   5612 ** EXPERIMENTAL
   5613 **
   5614 ** These constants are the available integer "verbs" that can be passed as
   5615 ** the second argument to the [sqlite3_db_status()] interface.
   5616 **
   5617 ** New verbs may be added in future releases of SQLite. Existing verbs
   5618 ** might be discontinued. Applications should check the return code from
   5619 ** [sqlite3_db_status()] to make sure that the call worked.
   5620 ** The [sqlite3_db_status()] interface will return a non-zero error code
   5621 ** if a discontinued or unsupported verb is invoked.
   5622 **
   5623 ** <dl>
   5624 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   5625 ** <dd>This parameter returns the number of lookaside memory slots currently
   5626 ** checked out.</dd>)^
   5627 ** </dl>
   5628 */
   5629 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
   5630 
   5631 
   5632 /*
   5633 ** CAPI3REF: Prepared Statement Status
   5634 ** EXPERIMENTAL
   5635 **
   5636 ** ^(Each prepared statement maintains various
   5637 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
   5638 ** of times it has performed specific operations.)^  These counters can
   5639 ** be used to monitor the performance characteristics of the prepared
   5640 ** statements.  For example, if the number of table steps greatly exceeds
   5641 ** the number of table searches or result rows, that would tend to indicate
   5642 ** that the prepared statement is using a full table scan rather than
   5643 ** an index.
   5644 **
   5645 ** ^(This interface is used to retrieve and reset counter values from
   5646 ** a [prepared statement].  The first argument is the prepared statement
   5647 ** object to be interrogated.  The second argument
   5648 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
   5649 ** to be interrogated.)^
   5650 ** ^The current value of the requested counter is returned.
   5651 ** ^If the resetFlg is true, then the counter is reset to zero after this
   5652 ** interface call returns.
   5653 **
   5654 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   5655 */
   5656 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   5657 
   5658 /*
   5659 ** CAPI3REF: Status Parameters for prepared statements
   5660 ** EXPERIMENTAL
   5661 **
   5662 ** These preprocessor macros define integer codes that name counter
   5663 ** values associated with the [sqlite3_stmt_status()] interface.
   5664 ** The meanings of the various counters are as follows:
   5665 **
   5666 ** <dl>
   5667 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   5668 ** <dd>^This is the number of times that SQLite has stepped forward in
   5669 ** a table as part of a full table scan.  Large numbers for this counter
   5670 ** may indicate opportunities for performance improvement through
   5671 ** careful use of indices.</dd>
   5672 **
   5673 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
   5674 ** <dd>^This is the number of sort operations that have occurred.
   5675 ** A non-zero value in this counter may indicate an opportunity to
   5676 ** improvement performance through careful use of indices.</dd>
   5677 **
   5678 ** </dl>
   5679 */
   5680 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   5681 #define SQLITE_STMTSTATUS_SORT              2
   5682 
   5683 /*
   5684 ** CAPI3REF: Custom Page Cache Object
   5685 ** EXPERIMENTAL
   5686 **
   5687 ** The sqlite3_pcache type is opaque.  It is implemented by
   5688 ** the pluggable module.  The SQLite core has no knowledge of
   5689 ** its size or internal structure and never deals with the
   5690 ** sqlite3_pcache object except by holding and passing pointers
   5691 ** to the object.
   5692 **
   5693 ** See [sqlite3_pcache_methods] for additional information.
   5694 */
   5695 typedef struct sqlite3_pcache sqlite3_pcache;
   5696 
   5697 /*
   5698 ** CAPI3REF: Application Defined Page Cache.
   5699 ** KEYWORDS: {page cache}
   5700 ** EXPERIMENTAL
   5701 **
   5702 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
   5703 ** register an alternative page cache implementation by passing in an
   5704 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the
   5705 ** heap memory used by SQLite is used by the page cache to cache data read
   5706 ** from, or ready to be written to, the database file. By implementing a
   5707 ** custom page cache using this API, an application can control more
   5708 ** precisely the amount of memory consumed by SQLite, the way in which
   5709 ** that memory is allocated and released, and the policies used to
   5710 ** determine exactly which parts of a database file are cached and for
   5711 ** how long.
   5712 **
   5713 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
   5714 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   5715 ** the application may discard the parameter after the call to
   5716 ** [sqlite3_config()] returns.)^
   5717 **
   5718 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
   5719 ** (usually only once during the lifetime of the process). ^(The xInit()
   5720 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
   5721 ** ^The xInit() method can set up up global structures and/or any mutexes
   5722 ** required by the custom page cache implementation.
   5723 **
   5724 ** ^The xShutdown() method is called from within [sqlite3_shutdown()],
   5725 ** if the application invokes this API. It can be used to clean up
   5726 ** any outstanding resources before process shutdown, if required.
   5727 **
   5728 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
   5729 ** the xInit method, so the xInit method need not be threadsafe.  ^The
   5730 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   5731 ** not need to be threadsafe either.  All other methods must be threadsafe
   5732 ** in multithreaded applications.
   5733 **
   5734 ** ^SQLite will never invoke xInit() more than once without an intervening
   5735 ** call to xShutdown().
   5736 **
   5737 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
   5738 ** will typically create one cache instance for each open database file,
   5739 ** though this is not guaranteed. ^The
   5740 ** first parameter, szPage, is the size in bytes of the pages that must
   5741 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
   5742 ** will the page size of the database file that is to be cached plus an
   5743 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
   5744 ** extra R bytes on each page to store metadata about the underlying
   5745 ** database page on disk.  The value of R depends
   5746 ** on the SQLite version, the target platform, and how SQLite was compiled.
   5747 ** ^R is constant for a particular build of SQLite.  ^The second argument to
   5748 ** xCreate(), bPurgeable, is true if the cache being created will
   5749 ** be used to cache database pages of a file stored on disk, or
   5750 ** false if it is used for an in-memory database. ^The cache implementation
   5751 ** does not have to do anything special based with the value of bPurgeable;
   5752 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   5753 ** never invoke xUnpin() except to deliberately delete a page.
   5754 ** ^In other words, a cache created with bPurgeable set to false will
   5755 ** never contain any unpinned pages.
   5756 **
   5757 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   5758 ** suggested maximum cache-size (number of pages stored by) the cache
   5759 ** instance passed as the first argument. This is the value configured using
   5760 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
   5761 ** parameter, the implementation is not required to do anything with this
   5762 ** value; it is advisory only.
   5763 **
   5764 ** ^The xPagecount() method should return the number of pages currently
   5765 ** stored in the cache.
   5766 **
   5767 ** ^The xFetch() method is used to fetch a page and return a pointer to it.
   5768 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
   5769 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
   5770 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
   5771 ** is considered to be "pinned".
   5772 **
   5773 ** ^If the requested page is already in the page cache, then the page cache
   5774 ** implementation must return a pointer to the page buffer with its content
   5775 ** intact.  ^(If the requested page is not already in the cache, then the
   5776 ** behavior of the cache implementation is determined by the value of the
   5777 ** createFlag parameter passed to xFetch, according to the following table:
   5778 **
   5779 ** <table border=1 width=85% align=center>
   5780 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
   5781 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   5782 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   5783 **                 Otherwise return NULL.
   5784 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   5785 **                 NULL if allocating a new page is effectively impossible.
   5786 ** </table>)^
   5787 **
   5788 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
   5789 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
   5790 ** attempt to unpin one or more cache pages by spilling the content of
   5791 ** pinned pages to disk and synching the operating system disk cache. After
   5792 ** attempting to unpin pages, the xFetch() method will be invoked again with
   5793 ** a createFlag of 2.
   5794 **
   5795 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   5796 ** as its second argument. ^(If the third parameter, discard, is non-zero,
   5797 ** then the page should be evicted from the cache. In this case SQLite
   5798 ** assumes that the next time the page is retrieved from the cache using
   5799 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
   5800 ** zero, then the page is considered to be unpinned. ^The cache implementation
   5801 ** may choose to evict unpinned pages at any time.
   5802 **
   5803 ** ^(The cache is not required to perform any reference counting. A single
   5804 ** call to xUnpin() unpins the page regardless of the number of prior calls
   5805 ** to xFetch().)^
   5806 **
   5807 ** ^The xRekey() method is used to change the key value associated with the
   5808 ** page passed as the second argument from oldKey to newKey. ^If the cache
   5809 ** previously contains an entry associated with newKey, it should be
   5810 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   5811 ** to be pinned.
   5812 **
   5813 ** ^When SQLite calls the xTruncate() method, the cache must discard all
   5814 ** existing cache entries with page numbers (keys) greater than or equal
   5815 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
   5816 ** of these pages are pinned, they are implicitly unpinned, meaning that
   5817 ** they can be safely discarded.
   5818 **
   5819 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   5820 ** All resources associated with the specified cache should be freed. ^After
   5821 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   5822 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
   5823 ** functions.
   5824 */
   5825 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   5826 struct sqlite3_pcache_methods {
   5827   void *pArg;
   5828   int (*xInit)(void*);
   5829   void (*xShutdown)(void*);
   5830   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   5831   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   5832   int (*xPagecount)(sqlite3_pcache*);
   5833   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   5834   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   5835   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   5836   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   5837   void (*xDestroy)(sqlite3_pcache*);
   5838 };
   5839 
   5840 /*
   5841 ** CAPI3REF: Online Backup Object
   5842 ** EXPERIMENTAL
   5843 **
   5844 ** The sqlite3_backup object records state information about an ongoing
   5845 ** online backup operation.  ^The sqlite3_backup object is created by
   5846 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   5847 ** [sqlite3_backup_finish()].
   5848 **
   5849 ** See Also: [Using the SQLite Online Backup API]
   5850 */
   5851 typedef struct sqlite3_backup sqlite3_backup;
   5852 
   5853 /*
   5854 ** CAPI3REF: Online Backup API.
   5855 ** EXPERIMENTAL
   5856 **
   5857 ** The backup API copies the content of one database into another.
   5858 ** It is useful either for creating backups of databases or
   5859 ** for copying in-memory databases to or from persistent files.
   5860 **
   5861 ** See Also: [Using the SQLite Online Backup API]
   5862 **
   5863 ** ^Exclusive access is required to the destination database for the
   5864 ** duration of the operation. ^However the source database is only
   5865 ** read-locked while it is actually being read; it is not locked
   5866 ** continuously for the entire backup operation. ^Thus, the backup may be
   5867 ** performed on a live source database without preventing other users from
   5868 ** reading or writing to the source database while the backup is underway.
   5869 **
   5870 ** ^(To perform a backup operation:
   5871 **   <ol>
   5872 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   5873 **         backup,
   5874 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   5875 **         the data between the two databases, and finally
   5876 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   5877 **         associated with the backup operation.
   5878 **   </ol>)^
   5879 ** There should be exactly one call to sqlite3_backup_finish() for each
   5880 ** successful call to sqlite3_backup_init().
   5881 **
   5882 ** <b>sqlite3_backup_init()</b>
   5883 **
   5884 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   5885 ** [database connection] associated with the destination database
   5886 ** and the database name, respectively.
   5887 ** ^The database name is "main" for the main database, "temp" for the
   5888 ** temporary database, or the name specified after the AS keyword in
   5889 ** an [ATTACH] statement for an attached database.
   5890 ** ^The S and M arguments passed to
   5891 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   5892 ** and database name of the source database, respectively.
   5893 ** ^The source and destination [database connections] (parameters S and D)
   5894 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
   5895 ** an error.
   5896 **
   5897 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   5898 ** returned and an error code and error message are store3d in the
   5899 ** destination [database connection] D.
   5900 ** ^The error code and message for the failed call to sqlite3_backup_init()
   5901 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   5902 ** [sqlite3_errmsg16()] functions.
   5903 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   5904 ** [sqlite3_backup] object.
   5905 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   5906 ** sqlite3_backup_finish() functions to perform the specified backup
   5907 ** operation.
   5908 **
   5909 ** <b>sqlite3_backup_step()</b>
   5910 **
   5911 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   5912 ** the source and destination databases specified by [sqlite3_backup] object B.
   5913 ** ^If N is negative, all remaining source pages are copied.
   5914 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   5915 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
   5916 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   5917 ** from source to destination, then it returns [SQLITE_DONE].
   5918 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   5919 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   5920 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   5921 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   5922 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   5923 **
   5924 ** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
   5925 ** database was opened read-only or if
   5926 ** the destination is an in-memory database with a different page size
   5927 ** from the source database.
   5928 **
   5929 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   5930 ** the [sqlite3_busy_handler | busy-handler function]
   5931 ** is invoked (if one is specified). ^If the
   5932 ** busy-handler returns non-zero before the lock is available, then
   5933 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   5934 ** sqlite3_backup_step() can be retried later. ^If the source
   5935 ** [database connection]
   5936 ** is being used to write to the source database when sqlite3_backup_step()
   5937 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   5938 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   5939 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   5940 ** [SQLITE_READONLY] is returned, then
   5941 ** there is no point in retrying the call to sqlite3_backup_step(). These
   5942 ** errors are considered fatal.)^  The application must accept
   5943 ** that the backup operation has failed and pass the backup operation handle
   5944 ** to the sqlite3_backup_finish() to release associated resources.
   5945 **
   5946 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   5947 ** on the destination file. ^The exclusive lock is not released until either
   5948 ** sqlite3_backup_finish() is called or the backup operation is complete
   5949 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   5950 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   5951 ** lasts for the duration of the sqlite3_backup_step() call.
   5952 ** ^Because the source database is not locked between calls to
   5953 ** sqlite3_backup_step(), the source database may be modified mid-way
   5954 ** through the backup process.  ^If the source database is modified by an
   5955 ** external process or via a database connection other than the one being
   5956 ** used by the backup operation, then the backup will be automatically
   5957 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   5958 ** database is modified by the using the same database connection as is used
   5959 ** by the backup operation, then the backup database is automatically
   5960 ** updated at the same time.
   5961 **
   5962 ** <b>sqlite3_backup_finish()</b>
   5963 **
   5964 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   5965 ** application wishes to abandon the backup operation, the application
   5966 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   5967 ** ^The sqlite3_backup_finish() interfaces releases all
   5968 ** resources associated with the [sqlite3_backup] object.
   5969 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   5970 ** active write-transaction on the destination database is rolled back.
   5971 ** The [sqlite3_backup] object is invalid
   5972 ** and may not be used following a call to sqlite3_backup_finish().
   5973 **
   5974 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   5975 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   5976 ** sqlite3_backup_step() completed.
   5977 ** ^If an out-of-memory condition or IO error occurred during any prior
   5978 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   5979 ** sqlite3_backup_finish() returns the corresponding [error code].
   5980 **
   5981 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   5982 ** is not a permanent error and does not affect the return value of
   5983 ** sqlite3_backup_finish().
   5984 **
   5985 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
   5986 **
   5987 ** ^Each call to sqlite3_backup_step() sets two values inside
   5988 ** the [sqlite3_backup] object: the number of pages still to be backed
   5989 ** up and the total number of pages in the source databae file.
   5990 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
   5991 ** retrieve these two values, respectively.
   5992 **
   5993 ** ^The values returned by these functions are only updated by
   5994 ** sqlite3_backup_step(). ^If the source database is modified during a backup
   5995 ** operation, then the values are not updated to account for any extra
   5996 ** pages that need to be updated or the size of the source database file
   5997 ** changing.
   5998 **
   5999 ** <b>Concurrent Usage of Database Handles</b>
   6000 **
   6001 ** ^The source [database connection] may be used by the application for other
   6002 ** purposes while a backup operation is underway or being initialized.
   6003 ** ^If SQLite is compiled and configured to support threadsafe database
   6004 ** connections, then the source database connection may be used concurrently
   6005 ** from within other threads.
   6006 **
   6007 ** However, the application must guarantee that the destination
   6008 ** [database connection] is not passed to any other API (by any thread) after
   6009 ** sqlite3_backup_init() is called and before the corresponding call to
   6010 ** sqlite3_backup_finish().  SQLite does not currently check to see
   6011 ** if the application incorrectly accesses the destination [database connection]
   6012 ** and so no error code is reported, but the operations may malfunction
   6013 ** nevertheless.  Use of the destination database connection while a
   6014 ** backup is in progress might also also cause a mutex deadlock.
   6015 **
   6016 ** If running in [shared cache mode], the application must
   6017 ** guarantee that the shared cache used by the destination database
   6018 ** is not accessed while the backup is running. In practice this means
   6019 ** that the application must guarantee that the disk file being
   6020 ** backed up to is not accessed by any connection within the process,
   6021 ** not just the specific connection that was passed to sqlite3_backup_init().
   6022 **
   6023 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   6024 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   6025 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   6026 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   6027 ** same time as another thread is invoking sqlite3_backup_step() it is
   6028 ** possible that they return invalid values.
   6029 */
   6030 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   6031   sqlite3 *pDest,                        /* Destination database handle */
   6032   const char *zDestName,                 /* Destination database name */
   6033   sqlite3 *pSource,                      /* Source database handle */
   6034   const char *zSourceName                /* Source database name */
   6035 );
   6036 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   6037 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   6038 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   6039 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   6040 
   6041 /*
   6042 ** CAPI3REF: Unlock Notification
   6043 ** EXPERIMENTAL
   6044 **
   6045 ** ^When running in shared-cache mode, a database operation may fail with
   6046 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   6047 ** individual tables within the shared-cache cannot be obtained. See
   6048 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   6049 ** ^This API may be used to register a callback that SQLite will invoke
   6050 ** when the connection currently holding the required lock relinquishes it.
   6051 ** ^This API is only available if the library was compiled with the
   6052 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   6053 **
   6054 ** See Also: [Using the SQLite Unlock Notification Feature].
   6055 **
   6056 ** ^Shared-cache locks are released when a database connection concludes
   6057 ** its current transaction, either by committing it or rolling it back.
   6058 **
   6059 ** ^When a connection (known as the blocked connection) fails to obtain a
   6060 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   6061 ** identity of the database connection (the blocking connection) that
   6062 ** has locked the required resource is stored internally. ^After an
   6063 ** application receives an SQLITE_LOCKED error, it may call the
   6064 ** sqlite3_unlock_notify() method with the blocked connection handle as
   6065 ** the first argument to register for a callback that will be invoked
   6066 ** when the blocking connections current transaction is concluded. ^The
   6067 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   6068 ** call that concludes the blocking connections transaction.
   6069 **
   6070 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   6071 ** there is a chance that the blocking connection will have already
   6072 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   6073 ** If this happens, then the specified callback is invoked immediately,
   6074 ** from within the call to sqlite3_unlock_notify().)^
   6075 **
   6076 ** ^If the blocked connection is attempting to obtain a write-lock on a
   6077 ** shared-cache table, and more than one other connection currently holds
   6078 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   6079 ** the other connections to use as the blocking connection.
   6080 **
   6081 ** ^(There may be at most one unlock-notify callback registered by a
   6082 ** blocked connection. If sqlite3_unlock_notify() is called when the
   6083 ** blocked connection already has a registered unlock-notify callback,
   6084 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   6085 ** called with a NULL pointer as its second argument, then any existing
   6086 ** unlock-notify callback is cancelled. ^The blocked connections
   6087 ** unlock-notify callback may also be canceled by closing the blocked
   6088 ** connection using [sqlite3_close()].
   6089 **
   6090 ** The unlock-notify callback is not reentrant. If an application invokes
   6091 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   6092 ** crash or deadlock may be the result.
   6093 **
   6094 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   6095 ** returns SQLITE_OK.
   6096 **
   6097 ** <b>Callback Invocation Details</b>
   6098 **
   6099 ** When an unlock-notify callback is registered, the application provides a
   6100 ** single void* pointer that is passed to the callback when it is invoked.
   6101 ** However, the signature of the callback function allows SQLite to pass
   6102 ** it an array of void* context pointers. The first argument passed to
   6103 ** an unlock-notify callback is a pointer to an array of void* pointers,
   6104 ** and the second is the number of entries in the array.
   6105 **
   6106 ** When a blocking connections transaction is concluded, there may be
   6107 ** more than one blocked connection that has registered for an unlock-notify
   6108 ** callback. ^If two or more such blocked connections have specified the
   6109 ** same callback function, then instead of invoking the callback function
   6110 ** multiple times, it is invoked once with the set of void* context pointers
   6111 ** specified by the blocked connections bundled together into an array.
   6112 ** This gives the application an opportunity to prioritize any actions
   6113 ** related to the set of unblocked database connections.
   6114 **
   6115 ** <b>Deadlock Detection</b>
   6116 **
   6117 ** Assuming that after registering for an unlock-notify callback a
   6118 ** database waits for the callback to be issued before taking any further
   6119 ** action (a reasonable assumption), then using this API may cause the
   6120 ** application to deadlock. For example, if connection X is waiting for
   6121 ** connection Y's transaction to be concluded, and similarly connection
   6122 ** Y is waiting on connection X's transaction, then neither connection
   6123 ** will proceed and the system may remain deadlocked indefinitely.
   6124 **
   6125 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   6126 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   6127 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   6128 ** unlock-notify callback is registered. The system is said to be in
   6129 ** a deadlocked state if connection A has registered for an unlock-notify
   6130 ** callback on the conclusion of connection B's transaction, and connection
   6131 ** B has itself registered for an unlock-notify callback when connection
   6132 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   6133 ** the system is also considered to be deadlocked if connection B has
   6134 ** registered for an unlock-notify callback on the conclusion of connection
   6135 ** C's transaction, where connection C is waiting on connection A. ^Any
   6136 ** number of levels of indirection are allowed.
   6137 **
   6138 ** <b>The "DROP TABLE" Exception</b>
   6139 **
   6140 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   6141 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   6142 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   6143 ** SQLite checks if there are any currently executing SELECT statements
   6144 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   6145 ** returned. In this case there is no "blocking connection", so invoking
   6146 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   6147 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   6148 ** or "DROP INDEX" query, an infinite loop might be the result.
   6149 **
   6150 ** One way around this problem is to check the extended error code returned
   6151 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   6152 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   6153 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   6154 ** SQLITE_LOCKED.)^
   6155 */
   6156 SQLITE_API int sqlite3_unlock_notify(
   6157   sqlite3 *pBlocked,                          /* Waiting connection */
   6158   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   6159   void *pNotifyArg                            /* Argument to pass to xNotify */
   6160 );
   6161 
   6162 
   6163 /*
   6164 ** CAPI3REF: String Comparison
   6165 ** EXPERIMENTAL
   6166 **
   6167 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
   6168 ** compare the contents of two buffers containing UTF-8 strings in a
   6169 ** case-indendent fashion, using the same definition of case independence
   6170 ** that SQLite uses internally when comparing identifiers.
   6171 */
   6172 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   6173 
   6174 /*
   6175 ** CAPI3REF: Error Logging Interface
   6176 ** EXPERIMENTAL
   6177 **
   6178 ** ^The [sqlite3_log()] interface writes a message into the error log
   6179 ** established by the [SQLITE_CONFIG_ERRORLOG] option to [sqlite3_config()].
   6180 **
   6181 ** The sqlite3_log() interface is intended for use by extensions such as
   6182 ** virtual tables, collating functions, and SQL functions.  While there is
   6183 ** nothing to prevent an application from calling sqlite3_log(), doing so
   6184 ** is considered bad form.
   6185 **
   6186 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   6187 ** will not use dynamically allocated memory.  The log message is stored in
   6188 ** a fixed-length buffer on the stack.  If the log message is longer than
   6189 ** a few hundred characters, it will be truncated to the length of the
   6190 ** buffer.
   6191 */
   6192 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   6193 
   6194 /*
   6195 ** Undo the hack that converts floating point types to integer for
   6196 ** builds on processors without floating point support.
   6197 */
   6198 #ifdef SQLITE_OMIT_FLOATING_POINT
   6199 # undef double
   6200 #endif
   6201 
   6202 #if 0
   6203 }  /* End of the 'extern "C"' block */
   6204 #endif
   6205 #endif
   6206 
   6207 
   6208 /************** End of sqlite3.h *********************************************/
   6209 // Begin Android Add
   6210 #define SQLITE_BeginImmediate 0x00200000  /* Default BEGIN to IMMEDIATE */
   6211 #define fdatasync fsync
   6212 #undef __APPLE__
   6213 // End Android Add
   6214 /************** Continuing where we left off in sqliteInt.h ******************/
   6215 /************** Include hash.h in the middle of sqliteInt.h ******************/
   6216 /************** Begin file hash.h ********************************************/
   6217 /*
   6218 ** 2001 September 22
   6219 **
   6220 ** The author disclaims copyright to this source code.  In place of
   6221 ** a legal notice, here is a blessing:
   6222 **
   6223 **    May you do good and not evil.
   6224 **    May you find forgiveness for yourself and forgive others.
   6225 **    May you share freely, never taking more than you give.
   6226 **
   6227 *************************************************************************
   6228 ** This is the header file for the generic hash-table implemenation
   6229 ** used in SQLite.
   6230 */
   6231 #ifndef _SQLITE_HASH_H_
   6232 #define _SQLITE_HASH_H_
   6233 
   6234 /* Forward declarations of structures. */
   6235 typedef struct Hash Hash;
   6236 typedef struct HashElem HashElem;
   6237 
   6238 /* A complete hash table is an instance of the following structure.
   6239 ** The internals of this structure are intended to be opaque -- client
   6240 ** code should not attempt to access or modify the fields of this structure
   6241 ** directly.  Change this structure only by using the routines below.
   6242 ** However, some of the "procedures" and "functions" for modifying and
   6243 ** accessing this structure are really macros, so we can't really make
   6244 ** this structure opaque.
   6245 **
   6246 ** All elements of the hash table are on a single doubly-linked list.
   6247 ** Hash.first points to the head of this list.
   6248 **
   6249 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   6250 ** the global doubly-linked list.  The contents of the bucket are the
   6251 ** element pointed to plus the next _ht.count-1 elements in the list.
   6252 **
   6253 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   6254 ** by a linear search of the global list.  For small tables, the
   6255 ** Hash.ht table is never allocated because if there are few elements
   6256 ** in the table, it is faster to do a linear search than to manage
   6257 ** the hash table.
   6258 */
   6259 struct Hash {
   6260   unsigned int htsize;      /* Number of buckets in the hash table */
   6261   unsigned int count;       /* Number of entries in this table */
   6262   HashElem *first;          /* The first element of the array */
   6263   struct _ht {              /* the hash table */
   6264     int count;                 /* Number of entries with this hash */
   6265     HashElem *chain;           /* Pointer to first entry with this hash */
   6266   } *ht;
   6267 };
   6268 
   6269 /* Each element in the hash table is an instance of the following
   6270 ** structure.  All elements are stored on a single doubly-linked list.
   6271 **
   6272 ** Again, this structure is intended to be opaque, but it can't really
   6273 ** be opaque because it is used by macros.
   6274 */
   6275 struct HashElem {
   6276   HashElem *next, *prev;       /* Next and previous elements in the table */
   6277   void *data;                  /* Data associated with this element */
   6278   const char *pKey; int nKey;  /* Key associated with this element */
   6279 };
   6280 
   6281 /*
   6282 ** Access routines.  To delete, insert a NULL pointer.
   6283 */
   6284 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   6285 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
   6286 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
   6287 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   6288 
   6289 /*
   6290 ** Macros for looping over all elements of a hash table.  The idiom is
   6291 ** like this:
   6292 **
   6293 **   Hash h;
   6294 **   HashElem *p;
   6295 **   ...
   6296 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   6297 **     SomeStructure *pData = sqliteHashData(p);
   6298 **     // do something with pData
   6299 **   }
   6300 */
   6301 #define sqliteHashFirst(H)  ((H)->first)
   6302 #define sqliteHashNext(E)   ((E)->next)
   6303 #define sqliteHashData(E)   ((E)->data)
   6304 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   6305 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   6306 
   6307 /*
   6308 ** Number of entries in a hash table
   6309 */
   6310 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   6311 
   6312 #endif /* _SQLITE_HASH_H_ */
   6313 
   6314 /************** End of hash.h ************************************************/
   6315 /************** Continuing where we left off in sqliteInt.h ******************/
   6316 /************** Include parse.h in the middle of sqliteInt.h *****************/
   6317 /************** Begin file parse.h *******************************************/
   6318 #define TK_SEMI                            1
   6319 #define TK_EXPLAIN                         2
   6320 #define TK_QUERY                           3
   6321 #define TK_PLAN                            4
   6322 #define TK_BEGIN                           5
   6323 #define TK_TRANSACTION                     6
   6324 #define TK_DEFERRED                        7
   6325 #define TK_IMMEDIATE                       8
   6326 #define TK_EXCLUSIVE                       9
   6327 #define TK_COMMIT                         10
   6328 #define TK_END                            11
   6329 #define TK_ROLLBACK                       12
   6330 #define TK_SAVEPOINT                      13
   6331 #define TK_RELEASE                        14
   6332 #define TK_TO                             15
   6333 #define TK_TABLE                          16
   6334 #define TK_CREATE                         17
   6335 #define TK_IF                             18
   6336 #define TK_NOT                            19
   6337 #define TK_EXISTS                         20
   6338 #define TK_TEMP                           21
   6339 #define TK_LP                             22
   6340 #define TK_RP                             23
   6341 #define TK_AS                             24
   6342 #define TK_COMMA                          25
   6343 #define TK_ID                             26
   6344 #define TK_INDEXED                        27
   6345 #define TK_ABORT                          28
   6346 #define TK_ACTION                         29
   6347 #define TK_AFTER                          30
   6348 #define TK_ANALYZE                        31
   6349 #define TK_ASC                            32
   6350 #define TK_ATTACH                         33
   6351 #define TK_BEFORE                         34
   6352 #define TK_BY                             35
   6353 #define TK_CASCADE                        36
   6354 #define TK_CAST                           37
   6355 #define TK_COLUMNKW                       38
   6356 #define TK_CONFLICT                       39
   6357 #define TK_DATABASE                       40
   6358 #define TK_DESC                           41
   6359 #define TK_DETACH                         42
   6360 #define TK_EACH                           43
   6361 #define TK_FAIL                           44
   6362 #define TK_FOR                            45
   6363 #define TK_IGNORE                         46
   6364 #define TK_INITIALLY                      47
   6365 #define TK_INSTEAD                        48
   6366 #define TK_LIKE_KW                        49
   6367 #define TK_MATCH                          50
   6368 #define TK_NO                             51
   6369 #define TK_KEY                            52
   6370 #define TK_OF                             53
   6371 #define TK_OFFSET                         54
   6372 #define TK_PRAGMA                         55
   6373 #define TK_RAISE                          56
   6374 #define TK_REPLACE                        57
   6375 #define TK_RESTRICT                       58
   6376 #define TK_ROW                            59
   6377 #define TK_TRIGGER                        60
   6378 #define TK_VACUUM                         61
   6379 #define TK_VIEW                           62
   6380 #define TK_VIRTUAL                        63
   6381 #define TK_REINDEX                        64
   6382 #define TK_RENAME                         65
   6383 #define TK_CTIME_KW                       66
   6384 #define TK_ANY                            67
   6385 #define TK_OR                             68
   6386 #define TK_AND                            69
   6387 #define TK_IS                             70
   6388 #define TK_BETWEEN                        71
   6389 #define TK_IN                             72
   6390 #define TK_ISNULL                         73
   6391 #define TK_NOTNULL                        74
   6392 #define TK_NE                             75
   6393 #define TK_EQ                             76
   6394 #define TK_GT                             77
   6395 #define TK_LE                             78
   6396 #define TK_LT                             79
   6397 #define TK_GE                             80
   6398 #define TK_ESCAPE                         81
   6399 #define TK_BITAND                         82
   6400 #define TK_BITOR                          83
   6401 #define TK_LSHIFT                         84
   6402 #define TK_RSHIFT                         85
   6403 #define TK_PLUS                           86
   6404 #define TK_MINUS                          87
   6405 #define TK_STAR                           88
   6406 #define TK_SLASH                          89
   6407 #define TK_REM                            90
   6408 #define TK_CONCAT                         91
   6409 #define TK_COLLATE                        92
   6410 #define TK_BITNOT                         93
   6411 #define TK_STRING                         94
   6412 #define TK_JOIN_KW                        95
   6413 #define TK_CONSTRAINT                     96
   6414 #define TK_DEFAULT                        97
   6415 #define TK_NULL                           98
   6416 #define TK_PRIMARY                        99
   6417 #define TK_UNIQUE                         100
   6418 #define TK_CHECK                          101
   6419 #define TK_REFERENCES                     102
   6420 #define TK_AUTOINCR                       103
   6421 #define TK_ON                             104
   6422 #define TK_INSERT                         105
   6423 #define TK_DELETE                         106
   6424 #define TK_UPDATE                         107
   6425 #define TK_SET                            108
   6426 #define TK_DEFERRABLE                     109
   6427 #define TK_FOREIGN                        110
   6428 #define TK_DROP                           111
   6429 #define TK_UNION                          112
   6430 #define TK_ALL                            113
   6431 #define TK_EXCEPT                         114
   6432 #define TK_INTERSECT                      115
   6433 #define TK_SELECT                         116
   6434 #define TK_DISTINCT                       117
   6435 #define TK_DOT                            118
   6436 #define TK_FROM                           119
   6437 #define TK_JOIN                           120
   6438 #define TK_USING                          121
   6439 #define TK_ORDER                          122
   6440 #define TK_GROUP                          123
   6441 #define TK_HAVING                         124
   6442 #define TK_LIMIT                          125
   6443 #define TK_WHERE                          126
   6444 #define TK_INTO                           127
   6445 #define TK_VALUES                         128
   6446 #define TK_INTEGER                        129
   6447 #define TK_FLOAT                          130
   6448 #define TK_BLOB                           131
   6449 #define TK_REGISTER                       132
   6450 #define TK_VARIABLE                       133
   6451 #define TK_CASE                           134
   6452 #define TK_WHEN                           135
   6453 #define TK_THEN                           136
   6454 #define TK_ELSE                           137
   6455 #define TK_INDEX                          138
   6456 #define TK_ALTER                          139
   6457 #define TK_ADD                            140
   6458 #define TK_TO_TEXT                        141
   6459 #define TK_TO_BLOB                        142
   6460 #define TK_TO_NUMERIC                     143
   6461 #define TK_TO_INT                         144
   6462 #define TK_TO_REAL                        145
   6463 #define TK_ISNOT                          146
   6464 #define TK_END_OF_FILE                    147
   6465 #define TK_ILLEGAL                        148
   6466 #define TK_SPACE                          149
   6467 #define TK_UNCLOSED_STRING                150
   6468 #define TK_FUNCTION                       151
   6469 #define TK_COLUMN                         152
   6470 #define TK_AGG_FUNCTION                   153
   6471 #define TK_AGG_COLUMN                     154
   6472 #define TK_CONST_FUNC                     155
   6473 #define TK_UMINUS                         156
   6474 #define TK_UPLUS                          157
   6475 
   6476 /************** End of parse.h ***********************************************/
   6477 /************** Continuing where we left off in sqliteInt.h ******************/
   6478 #include <stdio.h>
   6479 #include <stdlib.h>
   6480 #include <string.h>
   6481 #include <assert.h>
   6482 #include <stddef.h>
   6483 
   6484 /*
   6485 ** If compiling for a processor that lacks floating point support,
   6486 ** substitute integer for floating-point
   6487 */
   6488 #ifdef SQLITE_OMIT_FLOATING_POINT
   6489 # define double sqlite_int64
   6490 # define LONGDOUBLE_TYPE sqlite_int64
   6491 # ifndef SQLITE_BIG_DBL
   6492 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   6493 # endif
   6494 # define SQLITE_OMIT_DATETIME_FUNCS 1
   6495 # define SQLITE_OMIT_TRACE 1
   6496 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   6497 # undef SQLITE_HAVE_ISNAN
   6498 #endif
   6499 #ifndef SQLITE_BIG_DBL
   6500 # define SQLITE_BIG_DBL (1e99)
   6501 #endif
   6502 
   6503 /*
   6504 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   6505 ** afterward. Having this macro allows us to cause the C compiler
   6506 ** to omit code used by TEMP tables without messy #ifndef statements.
   6507 */
   6508 #ifdef SQLITE_OMIT_TEMPDB
   6509 #define OMIT_TEMPDB 1
   6510 #else
   6511 #define OMIT_TEMPDB 0
   6512 #endif
   6513 
   6514 /*
   6515 ** If the following macro is set to 1, then NULL values are considered
   6516 ** distinct when determining whether or not two entries are the same
   6517 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
   6518 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
   6519 ** is the way things are suppose to work.
   6520 **
   6521 ** If the following macro is set to 0, the NULLs are indistinct for
   6522 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
   6523 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
   6524 ** work.
   6525 */
   6526 #define NULL_DISTINCT_FOR_UNIQUE 1
   6527 
   6528 /*
   6529 ** The "file format" number is an integer that is incremented whenever
   6530 ** the VDBE-level file format changes.  The following macros define the
   6531 ** the default file format for new databases and the maximum file format
   6532 ** that the library can read.
   6533 */
   6534 #define SQLITE_MAX_FILE_FORMAT 4
   6535 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   6536 # define SQLITE_DEFAULT_FILE_FORMAT 1
   6537 #endif
   6538 
   6539 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   6540 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   6541 #endif
   6542 
   6543 /*
   6544 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   6545 ** on the command-line
   6546 */
   6547 #ifndef SQLITE_TEMP_STORE
   6548 # define SQLITE_TEMP_STORE 1
   6549 #endif
   6550 
   6551 /*
   6552 ** GCC does not define the offsetof() macro so we'll have to do it
   6553 ** ourselves.
   6554 */
   6555 #ifndef offsetof
   6556 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   6557 #endif
   6558 
   6559 /*
   6560 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   6561 ** not, there are still machines out there that use EBCDIC.)
   6562 */
   6563 #if 'A' == '\301'
   6564 # define SQLITE_EBCDIC 1
   6565 #else
   6566 # define SQLITE_ASCII 1
   6567 #endif
   6568 
   6569 /*
   6570 ** Integers of known sizes.  These typedefs might change for architectures
   6571 ** where the sizes very.  Preprocessor macros are available so that the
   6572 ** types can be conveniently redefined at compile-type.  Like this:
   6573 **
   6574 **         cc '-DUINTPTR_TYPE=long long int' ...
   6575 */
   6576 #ifndef UINT32_TYPE
   6577 # ifdef HAVE_UINT32_T
   6578 #  define UINT32_TYPE uint32_t
   6579 # else
   6580 #  define UINT32_TYPE unsigned int
   6581 # endif
   6582 #endif
   6583 #ifndef UINT16_TYPE
   6584 # ifdef HAVE_UINT16_T
   6585 #  define UINT16_TYPE uint16_t
   6586 # else
   6587 #  define UINT16_TYPE unsigned short int
   6588 # endif
   6589 #endif
   6590 #ifndef INT16_TYPE
   6591 # ifdef HAVE_INT16_T
   6592 #  define INT16_TYPE int16_t
   6593 # else
   6594 #  define INT16_TYPE short int
   6595 # endif
   6596 #endif
   6597 #ifndef UINT8_TYPE
   6598 # ifdef HAVE_UINT8_T
   6599 #  define UINT8_TYPE uint8_t
   6600 # else
   6601 #  define UINT8_TYPE unsigned char
   6602 # endif
   6603 #endif
   6604 #ifndef INT8_TYPE
   6605 # ifdef HAVE_INT8_T
   6606 #  define INT8_TYPE int8_t
   6607 # else
   6608 #  define INT8_TYPE signed char
   6609 # endif
   6610 #endif
   6611 #ifndef LONGDOUBLE_TYPE
   6612 # define LONGDOUBLE_TYPE long double
   6613 #endif
   6614 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   6615 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   6616 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   6617 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   6618 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   6619 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   6620 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   6621 
   6622 /*
   6623 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   6624 ** that can be stored in a u32 without loss of data.  The value
   6625 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   6626 ** have to specify the value in the less intuitive manner shown:
   6627 */
   6628 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   6629 
   6630 /*
   6631 ** Macros to determine whether the machine is big or little endian,
   6632 ** evaluated at runtime.
   6633 */
   6634 #ifdef SQLITE_AMALGAMATION
   6635 SQLITE_PRIVATE const int sqlite3one = 1;
   6636 #else
   6637 SQLITE_PRIVATE const int sqlite3one;
   6638 #endif
   6639 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
   6640                              || defined(__x86_64) || defined(__x86_64__)
   6641 # define SQLITE_BIGENDIAN    0
   6642 # define SQLITE_LITTLEENDIAN 1
   6643 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   6644 #else
   6645 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   6646 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   6647 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   6648 #endif
   6649 
   6650 /*
   6651 ** Constants for the largest and smallest possible 64-bit signed integers.
   6652 ** These macros are designed to work correctly on both 32-bit and 64-bit
   6653 ** compilers.
   6654 */
   6655 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   6656 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   6657 
   6658 /*
   6659 ** Round up a number to the next larger multiple of 8.  This is used
   6660 ** to force 8-byte alignment on 64-bit architectures.
   6661 */
   6662 #define ROUND8(x)     (((x)+7)&~7)
   6663 
   6664 /*
   6665 ** Round down to the nearest multiple of 8
   6666 */
   6667 #define ROUNDDOWN8(x) ((x)&~7)
   6668 
   6669 /*
   6670 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   6671 ** macro is used only within assert() to verify that the code gets
   6672 ** all alignment restrictions correct.
   6673 **
   6674 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   6675 ** underlying malloc() implemention might return us 4-byte aligned
   6676 ** pointers.  In that case, only verify 4-byte alignment.
   6677 */
   6678 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   6679 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   6680 #else
   6681 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   6682 #endif
   6683 
   6684 
   6685 /*
   6686 ** An instance of the following structure is used to store the busy-handler
   6687 ** callback for a given sqlite handle.
   6688 **
   6689 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   6690 ** callback for the database handle. Each pager opened via the sqlite
   6691 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   6692 ** callback is currently invoked only from within pager.c.
   6693 */
   6694 typedef struct BusyHandler BusyHandler;
   6695 struct BusyHandler {
   6696   int (*xFunc)(void *,int);  /* The busy callback */
   6697   void *pArg;                /* First arg to busy callback */
   6698   int nBusy;                 /* Incremented with each busy call */
   6699 };
   6700 
   6701 /*
   6702 ** Name of the master database table.  The master database table
   6703 ** is a special table that holds the names and attributes of all
   6704 ** user tables and indices.
   6705 */
   6706 #define MASTER_NAME       "sqlite_master"
   6707 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   6708 
   6709 /*
   6710 ** The root-page of the master database table.
   6711 */
   6712 #define MASTER_ROOT       1
   6713 
   6714 /*
   6715 ** The name of the schema table.
   6716 */
   6717 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   6718 
   6719 /*
   6720 ** A convenience macro that returns the number of elements in
   6721 ** an array.
   6722 */
   6723 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   6724 
   6725 /*
   6726 ** The following value as a destructor means to use sqlite3DbFree().
   6727 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
   6728 */
   6729 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
   6730 
   6731 /*
   6732 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   6733 ** not support Writable Static Data (WSD) such as global and static variables.
   6734 ** All variables must either be on the stack or dynamically allocated from
   6735 ** the heap.  When WSD is unsupported, the variable declarations scattered
   6736 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   6737 ** macro is used for this purpose.  And instead of referencing the variable
   6738 ** directly, we use its constant as a key to lookup the run-time allocated
   6739 ** buffer that holds real variable.  The constant is also the initializer
   6740 ** for the run-time allocated buffer.
   6741 **
   6742 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   6743 ** macros become no-ops and have zero performance impact.
   6744 */
   6745 #ifdef SQLITE_OMIT_WSD
   6746   #define SQLITE_WSD const
   6747   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   6748   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   6749 SQLITE_API   int sqlite3_wsd_init(int N, int J);
   6750 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
   6751 #else
   6752   #define SQLITE_WSD
   6753   #define GLOBAL(t,v) v
   6754   #define sqlite3GlobalConfig sqlite3Config
   6755 #endif
   6756 
   6757 /*
   6758 ** The following macros are used to suppress compiler warnings and to
   6759 ** make it clear to human readers when a function parameter is deliberately
   6760 ** left unused within the body of a function. This usually happens when
   6761 ** a function is called via a function pointer. For example the
   6762 ** implementation of an SQL aggregate step callback may not use the
   6763 ** parameter indicating the number of arguments passed to the aggregate,
   6764 ** if it knows that this is enforced elsewhere.
   6765 **
   6766 ** When a function parameter is not used at all within the body of a function,
   6767 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   6768 ** However, these macros may also be used to suppress warnings related to
   6769 ** parameters that may or may not be used depending on compilation options.
   6770 ** For example those parameters only used in assert() statements. In these
   6771 ** cases the parameters are named as per the usual conventions.
   6772 */
   6773 #define UNUSED_PARAMETER(x) (void)(x)
   6774 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   6775 
   6776 /*
   6777 ** Forward references to structures
   6778 */
   6779 typedef struct AggInfo AggInfo;
   6780 typedef struct AuthContext AuthContext;
   6781 typedef struct AutoincInfo AutoincInfo;
   6782 typedef struct Bitvec Bitvec;
   6783 typedef struct RowSet RowSet;
   6784 typedef struct CollSeq CollSeq;
   6785 typedef struct Column Column;
   6786 typedef struct Db Db;
   6787 typedef struct Schema Schema;
   6788 typedef struct Expr Expr;
   6789 typedef struct ExprList ExprList;
   6790 typedef struct ExprSpan ExprSpan;
   6791 typedef struct FKey FKey;
   6792 typedef struct FuncDef FuncDef;
   6793 typedef struct FuncDefHash FuncDefHash;
   6794 typedef struct IdList IdList;
   6795 typedef struct Index Index;
   6796 typedef struct IndexSample IndexSample;
   6797 typedef struct KeyClass KeyClass;
   6798 typedef struct KeyInfo KeyInfo;
   6799 typedef struct Lookaside Lookaside;
   6800 typedef struct LookasideSlot LookasideSlot;
   6801 typedef struct Module Module;
   6802 typedef struct NameContext NameContext;
   6803 typedef struct Parse Parse;
   6804 typedef struct Savepoint Savepoint;
   6805 typedef struct Select Select;
   6806 typedef struct SrcList SrcList;
   6807 typedef struct StrAccum StrAccum;
   6808 typedef struct Table Table;
   6809 typedef struct TableLock TableLock;
   6810 typedef struct Token Token;
   6811 typedef struct TriggerPrg TriggerPrg;
   6812 typedef struct TriggerStep TriggerStep;
   6813 typedef struct Trigger Trigger;
   6814 typedef struct UnpackedRecord UnpackedRecord;
   6815 typedef struct VTable VTable;
   6816 typedef struct Walker Walker;
   6817 typedef struct WherePlan WherePlan;
   6818 typedef struct WhereInfo WhereInfo;
   6819 typedef struct WhereLevel WhereLevel;
   6820 
   6821 /*
   6822 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   6823 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   6824 ** pointer types (i.e. FuncDef) defined above.
   6825 */
   6826 /************** Include btree.h in the middle of sqliteInt.h *****************/
   6827 /************** Begin file btree.h *******************************************/
   6828 /*
   6829 ** 2001 September 15
   6830 **
   6831 ** The author disclaims copyright to this source code.  In place of
   6832 ** a legal notice, here is a blessing:
   6833 **
   6834 **    May you do good and not evil.
   6835 **    May you find forgiveness for yourself and forgive others.
   6836 **    May you share freely, never taking more than you give.
   6837 **
   6838 *************************************************************************
   6839 ** This header file defines the interface that the sqlite B-Tree file
   6840 ** subsystem.  See comments in the source code for a detailed description
   6841 ** of what each interface routine does.
   6842 */
   6843 #ifndef _BTREE_H_
   6844 #define _BTREE_H_
   6845 
   6846 /* TODO: This definition is just included so other modules compile. It
   6847 ** needs to be revisited.
   6848 */
   6849 #define SQLITE_N_BTREE_META 10
   6850 
   6851 /*
   6852 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   6853 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   6854 */
   6855 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   6856   #define SQLITE_DEFAULT_AUTOVACUUM 0
   6857 #endif
   6858 
   6859 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   6860 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   6861 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   6862 
   6863 /*
   6864 ** Forward declarations of structure
   6865 */
   6866 typedef struct Btree Btree;
   6867 typedef struct BtCursor BtCursor;
   6868 typedef struct BtShared BtShared;
   6869 typedef struct BtreeMutexArray BtreeMutexArray;
   6870 
   6871 /*
   6872 ** This structure records all of the Btrees that need to hold
   6873 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
   6874 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
   6875 ** we can always lock and unlock them all quickly.
   6876 */
   6877 struct BtreeMutexArray {
   6878   int nMutex;
   6879   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
   6880 };
   6881 
   6882 
   6883 SQLITE_PRIVATE int sqlite3BtreeOpen(
   6884   const char *zFilename,   /* Name of database file to open */
   6885   sqlite3 *db,             /* Associated database connection */
   6886   Btree **ppBtree,         /* Return open Btree* here */
   6887   int flags,               /* Flags */
   6888   int vfsFlags             /* Flags passed through to VFS open */
   6889 );
   6890 
   6891 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   6892 ** following values.
   6893 **
   6894 ** NOTE:  These values must match the corresponding PAGER_ values in
   6895 ** pager.h.
   6896 */
   6897 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
   6898 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
   6899 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
   6900 #define BTREE_READONLY      8  /* Open the database in read-only mode */
   6901 #define BTREE_READWRITE    16  /* Open for both reading and writing */
   6902 #define BTREE_CREATE       32  /* Create the database if it does not exist */
   6903 
   6904 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   6905 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   6906 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
   6907 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
   6908 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   6909 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   6910 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   6911 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
   6912 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   6913 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   6914 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   6915 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   6916 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
   6917 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   6918 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
   6919 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   6920 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   6921 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   6922 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   6923 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   6924 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   6925 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   6926 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   6927 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   6928 
   6929 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   6930 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   6931 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   6932 
   6933 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   6934 
   6935 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   6936 ** of the following flags:
   6937 */
   6938 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   6939 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
   6940 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
   6941 
   6942 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   6943 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   6944 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
   6945 
   6946 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   6947 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   6948 
   6949 /*
   6950 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   6951 ** should be one of the following values. The integer values are assigned
   6952 ** to constants so that the offset of the corresponding field in an
   6953 ** SQLite database header may be found using the following formula:
   6954 **
   6955 **   offset = 36 + (idx * 4)
   6956 **
   6957 ** For example, the free-page-count field is located at byte offset 36 of
   6958 ** the database file header. The incr-vacuum-flag field is located at
   6959 ** byte offset 64 (== 36+4*7).
   6960 */
   6961 #define BTREE_FREE_PAGE_COUNT     0
   6962 #define BTREE_SCHEMA_VERSION      1
   6963 #define BTREE_FILE_FORMAT         2
   6964 #define BTREE_DEFAULT_CACHE_SIZE  3
   6965 #define BTREE_LARGEST_ROOT_PAGE   4
   6966 #define BTREE_TEXT_ENCODING       5
   6967 #define BTREE_USER_VERSION        6
   6968 #define BTREE_INCR_VACUUM         7
   6969 
   6970 SQLITE_PRIVATE int sqlite3BtreeCursor(
   6971   Btree*,                              /* BTree containing table to open */
   6972   int iTable,                          /* Index of root page */
   6973   int wrFlag,                          /* 1 for writing.  0 for read-only */
   6974   struct KeyInfo*,                     /* First argument to compare function */
   6975   BtCursor *pCursor                    /* Space to write cursor structure */
   6976 );
   6977 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   6978 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   6979 
   6980 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   6981 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   6982   BtCursor*,
   6983   UnpackedRecord *pUnKey,
   6984   i64 intKey,
   6985   int bias,
   6986   int *pRes
   6987 );
   6988 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
   6989 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
   6990 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
   6991                                   const void *pData, int nData,
   6992                                   int nZero, int bias, int seekResult);
   6993 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   6994 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   6995 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
   6996 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   6997 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
   6998 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   6999 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   7000 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
   7001 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
   7002 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   7003 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   7004 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
   7005 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
   7006 
   7007 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   7008 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   7009 
   7010 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   7011 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
   7012 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   7013 
   7014 #ifndef NDEBUG
   7015 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   7016 #endif
   7017 
   7018 #ifndef SQLITE_OMIT_BTREECOUNT
   7019 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   7020 #endif
   7021 
   7022 #ifdef SQLITE_TEST
   7023 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   7024 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   7025 #endif
   7026 
   7027 /*
   7028 ** If we are not using shared cache, then there is no need to
   7029 ** use mutexes to access the BtShared structures.  So make the
   7030 ** Enter and Leave procedures no-ops.
   7031 */
   7032 #ifndef SQLITE_OMIT_SHARED_CACHE
   7033 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   7034 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   7035 #else
   7036 # define sqlite3BtreeEnter(X)
   7037 # define sqlite3BtreeEnterAll(X)
   7038 #endif
   7039 
   7040 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   7041 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   7042 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   7043 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   7044 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   7045 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
   7046 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
   7047 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
   7048 #ifndef NDEBUG
   7049   /* These routines are used inside assert() statements only. */
   7050 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   7051 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   7052 #endif
   7053 #else
   7054 
   7055 # define sqlite3BtreeLeave(X)
   7056 # define sqlite3BtreeEnterCursor(X)
   7057 # define sqlite3BtreeLeaveCursor(X)
   7058 # define sqlite3BtreeLeaveAll(X)
   7059 # define sqlite3BtreeMutexArrayEnter(X)
   7060 # define sqlite3BtreeMutexArrayLeave(X)
   7061 # define sqlite3BtreeMutexArrayInsert(X,Y)
   7062 
   7063 # define sqlite3BtreeHoldsMutex(X) 1
   7064 # define sqlite3BtreeHoldsAllMutexes(X) 1
   7065 #endif
   7066 
   7067 
   7068 #endif /* _BTREE_H_ */
   7069 
   7070 /************** End of btree.h ***********************************************/
   7071 /************** Continuing where we left off in sqliteInt.h ******************/
   7072 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   7073 /************** Begin file vdbe.h ********************************************/
   7074 /*
   7075 ** 2001 September 15
   7076 **
   7077 ** The author disclaims copyright to this source code.  In place of
   7078 ** a legal notice, here is a blessing:
   7079 **
   7080 **    May you do good and not evil.
   7081 **    May you find forgiveness for yourself and forgive others.
   7082 **    May you share freely, never taking more than you give.
   7083 **
   7084 *************************************************************************
   7085 ** Header file for the Virtual DataBase Engine (VDBE)
   7086 **
   7087 ** This header defines the interface to the virtual database engine
   7088 ** or VDBE.  The VDBE implements an abstract machine that runs a
   7089 ** simple program to access and modify the underlying database.
   7090 */
   7091 #ifndef _SQLITE_VDBE_H_
   7092 #define _SQLITE_VDBE_H_
   7093 
   7094 /*
   7095 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   7096 ** in the source file sqliteVdbe.c are allowed to see the insides
   7097 ** of this structure.
   7098 */
   7099 typedef struct Vdbe Vdbe;
   7100 
   7101 /*
   7102 ** The names of the following types declared in vdbeInt.h are required
   7103 ** for the VdbeOp definition.
   7104 */
   7105 typedef struct VdbeFunc VdbeFunc;
   7106 typedef struct Mem Mem;
   7107 typedef struct SubProgram SubProgram;
   7108 
   7109 /*
   7110 ** A single instruction of the virtual machine has an opcode
   7111 ** and as many as three operands.  The instruction is recorded
   7112 ** as an instance of the following structure:
   7113 */
   7114 struct VdbeOp {
   7115   u8 opcode;          /* What operation to perform */
   7116   signed char p4type; /* One of the P4_xxx constants for p4 */
   7117   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
   7118   u8 p5;              /* Fifth parameter is an unsigned character */
   7119   int p1;             /* First operand */
   7120   int p2;             /* Second parameter (often the jump destination) */
   7121   int p3;             /* The third parameter */
   7122   union {             /* fourth parameter */
   7123     int i;                 /* Integer value if p4type==P4_INT32 */
   7124     void *p;               /* Generic pointer */
   7125     char *z;               /* Pointer to data for string (char array) types */
   7126     i64 *pI64;             /* Used when p4type is P4_INT64 */
   7127     double *pReal;         /* Used when p4type is P4_REAL */
   7128     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   7129     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
   7130     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   7131     Mem *pMem;             /* Used when p4type is P4_MEM */
   7132     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   7133     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   7134     int *ai;               /* Used when p4type is P4_INTARRAY */
   7135     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   7136   } p4;
   7137 #ifdef SQLITE_DEBUG
   7138   char *zComment;          /* Comment to improve readability */
   7139 #endif
   7140 #ifdef VDBE_PROFILE
   7141   int cnt;                 /* Number of times this instruction was executed */
   7142   u64 cycles;              /* Total time spent executing this instruction */
   7143 #endif
   7144 };
   7145 typedef struct VdbeOp VdbeOp;
   7146 
   7147 
   7148 /*
   7149 ** A sub-routine used to implement a trigger program.
   7150 */
   7151 struct SubProgram {
   7152   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   7153   int nOp;                      /* Elements in aOp[] */
   7154   int nMem;                     /* Number of memory cells required */
   7155   int nCsr;                     /* Number of cursors required */
   7156   int nRef;                     /* Number of pointers to this structure */
   7157   void *token;                  /* id that may be used to recursive triggers */
   7158 };
   7159 
   7160 /*
   7161 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   7162 ** it takes up less space.
   7163 */
   7164 struct VdbeOpList {
   7165   u8 opcode;          /* What operation to perform */
   7166   signed char p1;     /* First operand */
   7167   signed char p2;     /* Second parameter (often the jump destination) */
   7168   signed char p3;     /* Third parameter */
   7169 };
   7170 typedef struct VdbeOpList VdbeOpList;
   7171 
   7172 /*
   7173 ** Allowed values of VdbeOp.p4type
   7174 */
   7175 #define P4_NOTUSED    0   /* The P4 parameter is not used */
   7176 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
   7177 #define P4_STATIC   (-2)  /* Pointer to a static string */
   7178 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
   7179 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
   7180 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
   7181 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
   7182 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
   7183 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
   7184 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   7185 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   7186 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   7187 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   7188 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   7189 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
   7190 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   7191 
   7192 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
   7193 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
   7194 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
   7195 ** gets freed when the Vdbe is finalized so it still should be obtained
   7196 ** from a single sqliteMalloc().  But no copy is made and the calling
   7197 ** function should *not* try to free the KeyInfo.
   7198 */
   7199 #define P4_KEYINFO_HANDOFF (-16)
   7200 #define P4_KEYINFO_STATIC  (-17)
   7201 
   7202 /*
   7203 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   7204 ** number of columns of data returned by the statement.
   7205 */
   7206 #define COLNAME_NAME     0
   7207 #define COLNAME_DECLTYPE 1
   7208 #define COLNAME_DATABASE 2
   7209 #define COLNAME_TABLE    3
   7210 #define COLNAME_COLUMN   4
   7211 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   7212 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   7213 #else
   7214 # ifdef SQLITE_OMIT_DECLTYPE
   7215 #   define COLNAME_N      1      /* Store only the name */
   7216 # else
   7217 #   define COLNAME_N      2      /* Store the name and decltype */
   7218 # endif
   7219 #endif
   7220 
   7221 /*
   7222 ** The following macro converts a relative address in the p2 field
   7223 ** of a VdbeOp structure into a negative number so that
   7224 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   7225 ** the macro again restores the address.
   7226 */
   7227 #define ADDR(X)  (-1-(X))
   7228 
   7229 /*
   7230 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   7231 ** header file that defines a number for each opcode used by the VDBE.
   7232 */
   7233 /************** Include opcodes.h in the middle of vdbe.h ********************/
   7234 /************** Begin file opcodes.h *****************************************/
   7235 /* Automatically generated.  Do not edit */
   7236 /* See the mkopcodeh.awk script for details */
   7237 #define OP_Goto                                 1
   7238 #define OP_Gosub                                2
   7239 #define OP_Return                               3
   7240 #define OP_Yield                                4
   7241 #define OP_HaltIfNull                           5
   7242 #define OP_Halt                                 6
   7243 #define OP_Integer                              7
   7244 #define OP_Int64                                8
   7245 #define OP_Real                               130   /* same as TK_FLOAT    */
   7246 #define OP_String8                             94   /* same as TK_STRING   */
   7247 #define OP_String                               9
   7248 #define OP_Null                                10
   7249 #define OP_Blob                                11
   7250 #define OP_Variable                            12
   7251 #define OP_Move                                13
   7252 #define OP_Copy                                14
   7253 #define OP_SCopy                               15
   7254 #define OP_ResultRow                           16
   7255 #define OP_Concat                              91   /* same as TK_CONCAT   */
   7256 #define OP_Add                                 86   /* same as TK_PLUS     */
   7257 #define OP_Subtract                            87   /* same as TK_MINUS    */
   7258 #define OP_Multiply                            88   /* same as TK_STAR     */
   7259 #define OP_Divide                              89   /* same as TK_SLASH    */
   7260 #define OP_Remainder                           90   /* same as TK_REM      */
   7261 #define OP_CollSeq                             17
   7262 #define OP_Function                            18
   7263 #define OP_BitAnd                              82   /* same as TK_BITAND   */
   7264 #define OP_BitOr                               83   /* same as TK_BITOR    */
   7265 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
   7266 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
   7267 #define OP_AddImm                              20
   7268 #define OP_MustBeInt                           21
   7269 #define OP_RealAffinity                        22
   7270 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
   7271 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
   7272 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
   7273 #define OP_ToInt                              144   /* same as TK_TO_INT   */
   7274 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
   7275 #define OP_Eq                                  76   /* same as TK_EQ       */
   7276 #define OP_Ne                                  75   /* same as TK_NE       */
   7277 #define OP_Lt                                  79   /* same as TK_LT       */
   7278 #define OP_Le                                  78   /* same as TK_LE       */
   7279 #define OP_Gt                                  77   /* same as TK_GT       */
   7280 #define OP_Ge                                  80   /* same as TK_GE       */
   7281 #define OP_Permutation                         23
   7282 #define OP_Compare                             24
   7283 #define OP_Jump                                25
   7284 #define OP_And                                 69   /* same as TK_AND      */
   7285 #define OP_Or                                  68   /* same as TK_OR       */
   7286 #define OP_Not                                 19   /* same as TK_NOT      */
   7287 #define OP_BitNot                              93   /* same as TK_BITNOT   */
   7288 #define OP_If                                  26
   7289 #define OP_IfNot                               27
   7290 #define OP_IsNull                              73   /* same as TK_ISNULL   */
   7291 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
   7292 #define OP_Column                              28
   7293 #define OP_Affinity                            29
   7294 #define OP_MakeRecord                          30
   7295 #define OP_Count                               31
   7296 #define OP_Savepoint                           32
   7297 #define OP_AutoCommit                          33
   7298 #define OP_Transaction                         34
   7299 #define OP_ReadCookie                          35
   7300 #define OP_SetCookie                           36
   7301 #define OP_VerifyCookie                        37
   7302 #define OP_OpenRead                            38
   7303 #define OP_OpenWrite                           39
   7304 #define OP_OpenEphemeral                       40
   7305 #define OP_OpenPseudo                          41
   7306 #define OP_Close                               42
   7307 #define OP_SeekLt                              43
   7308 #define OP_SeekLe                              44
   7309 #define OP_SeekGe                              45
   7310 #define OP_SeekGt                              46
   7311 #define OP_Seek                                47
   7312 #define OP_NotFound                            48
   7313 #define OP_Found                               49
   7314 #define OP_IsUnique                            50
   7315 #define OP_NotExists                           51
   7316 #define OP_Sequence                            52
   7317 #define OP_NewRowid                            53
   7318 #define OP_Insert                              54
   7319 #define OP_InsertInt                           55
   7320 #define OP_Delete                              56
   7321 #define OP_ResetCount                          57
   7322 #define OP_RowKey                              58
   7323 #define OP_RowData                             59
   7324 #define OP_Rowid                               60
   7325 #define OP_NullRow                             61
   7326 #define OP_Last                                62
   7327 #define OP_Sort                                63
   7328 #define OP_Rewind                              64
   7329 #define OP_Prev                                65
   7330 #define OP_Next                                66
   7331 #define OP_IdxInsert                           67
   7332 #define OP_IdxDelete                           70
   7333 #define OP_IdxRowid                            71
   7334 #define OP_IdxLT                               72
   7335 #define OP_IdxGE                               81
   7336 #define OP_Destroy                             92
   7337 #define OP_Clear                               95
   7338 #define OP_CreateIndex                         96
   7339 #define OP_CreateTable                         97
   7340 #define OP_ParseSchema                         98
   7341 #define OP_LoadAnalysis                        99
   7342 #define OP_DropTable                          100
   7343 #define OP_DropIndex                          101
   7344 #define OP_DropTrigger                        102
   7345 #define OP_IntegrityCk                        103
   7346 #define OP_RowSetAdd                          104
   7347 #define OP_RowSetRead                         105
   7348 #define OP_RowSetTest                         106
   7349 #define OP_Program                            107
   7350 #define OP_Param                              108
   7351 #define OP_FkCounter                          109
   7352 #define OP_FkIfZero                           110
   7353 #define OP_MemMax                             111
   7354 #define OP_IfPos                              112
   7355 #define OP_IfNeg                              113
   7356 #define OP_IfZero                             114
   7357 #define OP_AggStep                            115
   7358 #define OP_AggFinal                           116
   7359 #define OP_Vacuum                             117
   7360 #define OP_IncrVacuum                         118
   7361 #define OP_Expire                             119
   7362 #define OP_TableLock                          120
   7363 #define OP_VBegin                             121
   7364 #define OP_VCreate                            122
   7365 #define OP_VDestroy                           123
   7366 #define OP_VOpen                              124
   7367 #define OP_VFilter                            125
   7368 #define OP_VColumn                            126
   7369 #define OP_VNext                              127
   7370 #define OP_VRename                            128
   7371 #define OP_VUpdate                            129
   7372 #define OP_Pagecount                          131
   7373 #define OP_Trace                              132
   7374 #define OP_Noop                               133
   7375 #define OP_Explain                            134
   7376 
   7377 /* The following opcode values are never used */
   7378 #define OP_NotUsed_135                        135
   7379 #define OP_NotUsed_136                        136
   7380 #define OP_NotUsed_137                        137
   7381 #define OP_NotUsed_138                        138
   7382 #define OP_NotUsed_139                        139
   7383 #define OP_NotUsed_140                        140
   7384 
   7385 
   7386 /* Properties such as "out2" or "jump" that are specified in
   7387 ** comments following the "case" for each opcode in the vdbe.c
   7388 ** are encoded into bitvectors as follows:
   7389 */
   7390 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
   7391 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
   7392 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
   7393 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
   7394 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
   7395 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
   7396 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
   7397 #define OPFLG_INITIALIZER {\
   7398 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
   7399 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
   7400 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
   7401 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
   7402 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
   7403 /*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
   7404 /*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
   7405 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
   7406 /*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
   7407 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
   7408 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
   7409 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
   7410 /*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   7411 /* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
   7412 /* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
   7413 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
   7414 /* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
   7415 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
   7416 /* 144 */ 0x04, 0x04,}
   7417 
   7418 /************** End of opcodes.h *********************************************/
   7419 /************** Continuing where we left off in vdbe.h ***********************/
   7420 
   7421 /*
   7422 ** Prototypes for the VDBE interface.  See comments on the implementation
   7423 ** for a description of what each of these routines does.
   7424 */
   7425 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
   7426 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   7427 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   7428 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   7429 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   7430 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   7431 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   7432 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
   7433 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
   7434 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
   7435 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
   7436 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   7437 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   7438 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
   7439 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   7440 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   7441 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   7442 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   7443 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   7444 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   7445 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
   7446 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   7447 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   7448 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   7449 #ifdef SQLITE_DEBUG
   7450 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   7451 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
   7452 #endif
   7453 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   7454 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   7455 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   7456 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   7457 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   7458 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   7459 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   7460 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   7461 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   7462 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
   7463 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
   7464 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   7465 #ifndef SQLITE_OMIT_TRACE
   7466 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   7467 #endif
   7468 
   7469 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
   7470 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
   7471 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
   7472 
   7473 
   7474 #ifndef NDEBUG
   7475 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   7476 # define VdbeComment(X)  sqlite3VdbeComment X
   7477 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   7478 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   7479 #else
   7480 # define VdbeComment(X)
   7481 # define VdbeNoopComment(X)
   7482 #endif
   7483 
   7484 #endif
   7485 
   7486 /************** End of vdbe.h ************************************************/
   7487 /************** Continuing where we left off in sqliteInt.h ******************/
   7488 /************** Include pager.h in the middle of sqliteInt.h *****************/
   7489 /************** Begin file pager.h *******************************************/
   7490 /*
   7491 ** 2001 September 15
   7492 **
   7493 ** The author disclaims copyright to this source code.  In place of
   7494 ** a legal notice, here is a blessing:
   7495 **
   7496 **    May you do good and not evil.
   7497 **    May you find forgiveness for yourself and forgive others.
   7498 **    May you share freely, never taking more than you give.
   7499 **
   7500 *************************************************************************
   7501 ** This header file defines the interface that the sqlite page cache
   7502 ** subsystem.  The page cache subsystem reads and writes a file a page
   7503 ** at a time and provides a journal for rollback.
   7504 */
   7505 
   7506 #ifndef _PAGER_H_
   7507 #define _PAGER_H_
   7508 
   7509 /*
   7510 ** Default maximum size for persistent journal files. A negative
   7511 ** value means no limit. This value may be overridden using the
   7512 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   7513 */
   7514 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   7515   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   7516 #endif
   7517 
   7518 /*
   7519 ** The type used to represent a page number.  The first page in a file
   7520 ** is called page 1.  0 is used to represent "not a page".
   7521 */
   7522 typedef u32 Pgno;
   7523 
   7524 /*
   7525 ** Each open file is managed by a separate instance of the "Pager" structure.
   7526 */
   7527 typedef struct Pager Pager;
   7528 
   7529 /*
   7530 ** Handle type for pages.
   7531 */
   7532 typedef struct PgHdr DbPage;
   7533 
   7534 /*
   7535 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   7536 ** reserved for working around a windows/posix incompatibility). It is
   7537 ** used in the journal to signify that the remainder of the journal file
   7538 ** is devoted to storing a master journal name - there are no more pages to
   7539 ** roll back. See comments for function writeMasterJournal() in pager.c
   7540 ** for details.
   7541 */
   7542 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   7543 
   7544 /*
   7545 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   7546 **
   7547 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   7548 */
   7549 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   7550 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
   7551 
   7552 /*
   7553 ** Valid values for the second argument to sqlite3PagerLockingMode().
   7554 */
   7555 #define PAGER_LOCKINGMODE_QUERY      -1
   7556 #define PAGER_LOCKINGMODE_NORMAL      0
   7557 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   7558 
   7559 /*
   7560 ** Valid values for the second argument to sqlite3PagerJournalMode().
   7561 */
   7562 #define PAGER_JOURNALMODE_QUERY      -1
   7563 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   7564 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   7565 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   7566 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   7567 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   7568 
   7569 /*
   7570 ** The remainder of this file contains the declarations of the functions
   7571 ** that make up the Pager sub-system API. See source code comments for
   7572 ** a detailed description of each routine.
   7573 */
   7574 
   7575 /* Open and close a Pager connection. */
   7576 SQLITE_PRIVATE int sqlite3PagerOpen(
   7577   sqlite3_vfs*,
   7578   Pager **ppPager,
   7579   const char*,
   7580   int,
   7581   int,
   7582   int,
   7583   void(*)(DbPage*)
   7584 );
   7585 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
   7586 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   7587 
   7588 /* Functions used to configure a Pager object. */
   7589 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   7590 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
   7591 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   7592 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   7593 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
   7594 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   7595 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
   7596 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   7597 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   7598 
   7599 /* Functions used to obtain and release page references. */
   7600 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   7601 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
   7602 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   7603 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   7604 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   7605 
   7606 /* Operations on page references. */
   7607 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   7608 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   7609 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   7610 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   7611 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   7612 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   7613 
   7614 /* Functions used to manage pager transactions and savepoints. */
   7615 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
   7616 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   7617 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   7618 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
   7619 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   7620 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   7621 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   7622 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   7623 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   7624 
   7625 /* Functions used to query pager state and configuration. */
   7626 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   7627 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
   7628 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
   7629 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
   7630 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   7631 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   7632 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
   7633 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   7634 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   7635 
   7636 /* Functions used to truncate the database file. */
   7637 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   7638 
   7639 /* Functions to support testing and debugging. */
   7640 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   7641 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   7642 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   7643 #endif
   7644 #ifdef SQLITE_TEST
   7645 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   7646 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   7647   void disable_simulated_io_errors(void);
   7648   void enable_simulated_io_errors(void);
   7649 #else
   7650 # define disable_simulated_io_errors()
   7651 # define enable_simulated_io_errors()
   7652 #endif
   7653 
   7654 #endif /* _PAGER_H_ */
   7655 
   7656 /************** End of pager.h ***********************************************/
   7657 /************** Continuing where we left off in sqliteInt.h ******************/
   7658 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   7659 /************** Begin file pcache.h ******************************************/
   7660 /*
   7661 ** 2008 August 05
   7662 **
   7663 ** The author disclaims copyright to this source code.  In place of
   7664 ** a legal notice, here is a blessing:
   7665 **
   7666 **    May you do good and not evil.
   7667 **    May you find forgiveness for yourself and forgive others.
   7668 **    May you share freely, never taking more than you give.
   7669 **
   7670 *************************************************************************
   7671 ** This header file defines the interface that the sqlite page cache
   7672 ** subsystem.
   7673 */
   7674 
   7675 #ifndef _PCACHE_H_
   7676 
   7677 typedef struct PgHdr PgHdr;
   7678 typedef struct PCache PCache;
   7679 
   7680 /*
   7681 ** Every page in the cache is controlled by an instance of the following
   7682 ** structure.
   7683 */
   7684 struct PgHdr {
   7685   void *pData;                   /* Content of this page */
   7686   void *pExtra;                  /* Extra content */
   7687   PgHdr *pDirty;                 /* Transient list of dirty pages */
   7688   Pgno pgno;                     /* Page number for this page */
   7689   Pager *pPager;                 /* The pager this page is part of */
   7690 #ifdef SQLITE_CHECK_PAGES
   7691   u32 pageHash;                  /* Hash of page content */
   7692 #endif
   7693   u16 flags;                     /* PGHDR flags defined below */
   7694 
   7695   /**********************************************************************
   7696   ** Elements above are public.  All that follows is private to pcache.c
   7697   ** and should not be accessed by other modules.
   7698   */
   7699   i16 nRef;                      /* Number of users of this page */
   7700   PCache *pCache;                /* Cache that owns this page */
   7701 
   7702   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   7703   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   7704 };
   7705 
   7706 /* Bit values for PgHdr.flags */
   7707 #define PGHDR_DIRTY             0x002  /* Page has changed */
   7708 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
   7709                                        ** writing this page to the database */
   7710 #define PGHDR_NEED_READ         0x008  /* Content is unread */
   7711 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
   7712 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
   7713 
   7714 /* Initialize and shutdown the page cache subsystem */
   7715 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   7716 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   7717 
   7718 /* Page cache buffer management:
   7719 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   7720 */
   7721 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   7722 
   7723 /* Create a new pager cache.
   7724 ** Under memory stress, invoke xStress to try to make pages clean.
   7725 ** Only clean and unpinned pages can be reclaimed.
   7726 */
   7727 SQLITE_PRIVATE void sqlite3PcacheOpen(
   7728   int szPage,                    /* Size of every page */
   7729   int szExtra,                   /* Extra space associated with each page */
   7730   int bPurgeable,                /* True if pages are on backing store */
   7731   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   7732   void *pStress,                 /* Argument to xStress */
   7733   PCache *pToInit                /* Preallocated space for the PCache */
   7734 );
   7735 
   7736 /* Modify the page-size after the cache has been created. */
   7737 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
   7738 
   7739 /* Return the size in bytes of a PCache object.  Used to preallocate
   7740 ** storage space.
   7741 */
   7742 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   7743 
   7744 /* One release per successful fetch.  Page is pinned until released.
   7745 ** Reference counted.
   7746 */
   7747 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
   7748 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   7749 
   7750 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   7751 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   7752 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   7753 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   7754 
   7755 /* Change a page number.  Used by incr-vacuum. */
   7756 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   7757 
   7758 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   7759 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   7760 
   7761 /* Get a list of all dirty pages in the cache, sorted by page number */
   7762 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   7763 
   7764 /* Reset and close the cache object */
   7765 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   7766 
   7767 /* Clear flags from pages of the page cache */
   7768 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   7769 
   7770 /* Discard the contents of the cache */
   7771 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   7772 
   7773 /* Return the total number of outstanding page references */
   7774 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   7775 
   7776 /* Increment the reference count of an existing page */
   7777 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   7778 
   7779 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   7780 
   7781 /* Return the total number of pages stored in the cache */
   7782 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   7783 
   7784 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   7785 /* Iterate through all dirty pages currently stored in the cache. This
   7786 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   7787 ** library is built.
   7788 */
   7789 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   7790 #endif
   7791 
   7792 /* Set and get the suggested cache-size for the specified pager-cache.
   7793 **
   7794 ** If no global maximum is configured, then the system attempts to limit
   7795 ** the total number of pages cached by purgeable pager-caches to the sum
   7796 ** of the suggested cache-sizes.
   7797 */
   7798 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   7799 #ifdef SQLITE_TEST
   7800 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   7801 #endif
   7802 
   7803 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   7804 /* Try to return memory used by the pcache module to the main memory heap */
   7805 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   7806 #endif
   7807 
   7808 #ifdef SQLITE_TEST
   7809 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   7810 #endif
   7811 
   7812 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   7813 
   7814 #endif /* _PCACHE_H_ */
   7815 
   7816 /************** End of pcache.h **********************************************/
   7817 /************** Continuing where we left off in sqliteInt.h ******************/
   7818 
   7819 /************** Include os.h in the middle of sqliteInt.h ********************/
   7820 /************** Begin file os.h **********************************************/
   7821 /*
   7822 ** 2001 September 16
   7823 **
   7824 ** The author disclaims copyright to this source code.  In place of
   7825 ** a legal notice, here is a blessing:
   7826 **
   7827 **    May you do good and not evil.
   7828 **    May you find forgiveness for yourself and forgive others.
   7829 **    May you share freely, never taking more than you give.
   7830 **
   7831 ******************************************************************************
   7832 **
   7833 ** This header file (together with is companion C source-code file
   7834 ** "os.c") attempt to abstract the underlying operating system so that
   7835 ** the SQLite library will work on both POSIX and windows systems.
   7836 **
   7837 ** This header file is #include-ed by sqliteInt.h and thus ends up
   7838 ** being included by every source file.
   7839 */
   7840 #ifndef _SQLITE_OS_H_
   7841 #define _SQLITE_OS_H_
   7842 
   7843 /*
   7844 ** Figure out if we are dealing with Unix, Windows, or some other
   7845 ** operating system.  After the following block of preprocess macros,
   7846 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
   7847 ** will defined to either 1 or 0.  One of the four will be 1.  The other
   7848 ** three will be 0.
   7849 */
   7850 #if defined(SQLITE_OS_OTHER)
   7851 # if SQLITE_OS_OTHER==1
   7852 #   undef SQLITE_OS_UNIX
   7853 #   define SQLITE_OS_UNIX 0
   7854 #   undef SQLITE_OS_WIN
   7855 #   define SQLITE_OS_WIN 0
   7856 #   undef SQLITE_OS_OS2
   7857 #   define SQLITE_OS_OS2 0
   7858 # else
   7859 #   undef SQLITE_OS_OTHER
   7860 # endif
   7861 #endif
   7862 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   7863 # define SQLITE_OS_OTHER 0
   7864 # ifndef SQLITE_OS_WIN
   7865 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
   7866 #     define SQLITE_OS_WIN 1
   7867 #     define SQLITE_OS_UNIX 0
   7868 #     define SQLITE_OS_OS2 0
   7869 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
   7870 #     define SQLITE_OS_WIN 0
   7871 #     define SQLITE_OS_UNIX 0
   7872 #     define SQLITE_OS_OS2 1
   7873 #   else
   7874 #     define SQLITE_OS_WIN 0
   7875 #     define SQLITE_OS_UNIX 1
   7876 #     define SQLITE_OS_OS2 0
   7877 #  endif
   7878 # else
   7879 #  define SQLITE_OS_UNIX 0
   7880 #  define SQLITE_OS_OS2 0
   7881 # endif
   7882 #else
   7883 # ifndef SQLITE_OS_WIN
   7884 #  define SQLITE_OS_WIN 0
   7885 # endif
   7886 #endif
   7887 
   7888 /*
   7889 ** Determine if we are dealing with WindowsCE - which has a much
   7890 ** reduced API.
   7891 */
   7892 #if defined(_WIN32_WCE)
   7893 # define SQLITE_OS_WINCE 1
   7894 #else
   7895 # define SQLITE_OS_WINCE 0
   7896 #endif
   7897 
   7898 
   7899 /*
   7900 ** Define the maximum size of a temporary filename
   7901 */
   7902 #if SQLITE_OS_WIN
   7903 # include <windows.h>
   7904 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
   7905 #elif SQLITE_OS_OS2
   7906 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
   7907 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
   7908 # endif
   7909 # define INCL_DOSDATETIME
   7910 # define INCL_DOSFILEMGR
   7911 # define INCL_DOSERRORS
   7912 # define INCL_DOSMISC
   7913 # define INCL_DOSPROCESS
   7914 # define INCL_DOSMODULEMGR
   7915 # define INCL_DOSSEMAPHORES
   7916 # include <os2.h>
   7917 # include <uconv.h>
   7918 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
   7919 #else
   7920 # define SQLITE_TEMPNAME_SIZE 200
   7921 #endif
   7922 
   7923 /* If the SET_FULLSYNC macro is not defined above, then make it
   7924 ** a no-op
   7925 */
   7926 #ifndef SET_FULLSYNC
   7927 # define SET_FULLSYNC(x,y)
   7928 #endif
   7929 
   7930 /*
   7931 ** The default size of a disk sector
   7932 */
   7933 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   7934 # define SQLITE_DEFAULT_SECTOR_SIZE 512
   7935 #endif
   7936 
   7937 /*
   7938 ** Temporary files are named starting with this prefix followed by 16 random
   7939 ** alphanumeric characters, and no file extension. They are stored in the
   7940 ** OS's standard temporary file directory, and are deleted prior to exit.
   7941 ** If sqlite is being embedded in another program, you may wish to change the
   7942 ** prefix to reflect your program's name, so that if your program exits
   7943 ** prematurely, old temporary files can be easily identified. This can be done
   7944 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   7945 **
   7946 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   7947 ** Mcafee started using SQLite in their anti-virus product and it
   7948 ** started putting files with the "sqlite" name in the c:/temp folder.
   7949 ** This annoyed many windows users.  Those users would then do a
   7950 ** Google search for "sqlite", find the telephone numbers of the
   7951 ** developers and call to wake them up at night and complain.
   7952 ** For this reason, the default name prefix is changed to be "sqlite"
   7953 ** spelled backwards.  So the temp files are still identified, but
   7954 ** anybody smart enough to figure out the code is also likely smart
   7955 ** enough to know that calling the developer will not help get rid
   7956 ** of the file.
   7957 */
   7958 #ifndef SQLITE_TEMP_FILE_PREFIX
   7959 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   7960 #endif
   7961 
   7962 /*
   7963 ** The following values may be passed as the second argument to
   7964 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   7965 **
   7966 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   7967 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   7968 **            any time. Other processes may hold and obtain new SHARED locks.
   7969 ** PENDING:   A single process may hold a PENDING lock on a file at
   7970 **            any one time. Existing SHARED locks may persist, but no new
   7971 **            SHARED locks may be obtained by other processes.
   7972 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   7973 **
   7974 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   7975 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   7976 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   7977 ** sqlite3OsLock().
   7978 */
   7979 #define NO_LOCK         0
   7980 #define SHARED_LOCK     1
   7981 #define RESERVED_LOCK   2
   7982 #define PENDING_LOCK    3
   7983 #define EXCLUSIVE_LOCK  4
   7984 
   7985 /*
   7986 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   7987 **
   7988 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   7989 ** those functions are not available.  So we use only LockFile() and
   7990 ** UnlockFile().
   7991 **
   7992 ** LockFile() prevents not just writing but also reading by other processes.
   7993 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   7994 ** byte out of a specific range of bytes. The lock byte is obtained at
   7995 ** random so two separate readers can probably access the file at the
   7996 ** same time, unless they are unlucky and choose the same lock byte.
   7997 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   7998 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   7999 ** a single byte of the file that is designated as the reserved lock byte.
   8000 ** A PENDING_LOCK is obtained by locking a designated byte different from
   8001 ** the RESERVED_LOCK byte.
   8002 **
   8003 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   8004 ** which means we can use reader/writer locks.  When reader/writer locks
   8005 ** are used, the lock is placed on the same range of bytes that is used
   8006 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   8007 ** will support two or more Win95 readers or two or more WinNT readers.
   8008 ** But a single Win95 reader will lock out all WinNT readers and a single
   8009 ** WinNT reader will lock out all other Win95 readers.
   8010 **
   8011 ** The following #defines specify the range of bytes used for locking.
   8012 ** SHARED_SIZE is the number of bytes available in the pool from which
   8013 ** a random byte is selected for a shared lock.  The pool of bytes for
   8014 ** shared locks begins at SHARED_FIRST.
   8015 **
   8016 ** The same locking strategy and
   8017 ** byte ranges are used for Unix.  This leaves open the possiblity of having
   8018 ** clients on win95, winNT, and unix all talking to the same shared file
   8019 ** and all locking correctly.  To do so would require that samba (or whatever
   8020 ** tool is being used for file sharing) implements locks correctly between
   8021 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   8022 ** using the same locking range we are at least open to the possibility.
   8023 **
   8024 ** Locking in windows is manditory.  For this reason, we cannot store
   8025 ** actual data in the bytes used for locking.  The pager never allocates
   8026 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   8027 ** that all locks will fit on a single page even at the minimum page size.
   8028 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   8029 ** is set high so that we don't have to allocate an unused page except
   8030 ** for very large databases.  But one should test the page skipping logic
   8031 ** by setting PENDING_BYTE low and running the entire regression suite.
   8032 **
   8033 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   8034 ** file format.  Depending on how it is changed, you might not notice
   8035 ** the incompatibility right away, even running a full regression test.
   8036 ** The default location of PENDING_BYTE is the first byte past the
   8037 ** 1GB boundary.
   8038 **
   8039 */
   8040 #define PENDING_BYTE      sqlite3PendingByte
   8041 #define RESERVED_BYTE     (PENDING_BYTE+1)
   8042 #define SHARED_FIRST      (PENDING_BYTE+2)
   8043 #define SHARED_SIZE       510
   8044 
   8045 /*
   8046 ** Wrapper around OS specific sqlite3_os_init() function.
   8047 */
   8048 SQLITE_PRIVATE int sqlite3OsInit(void);
   8049 
   8050 /*
   8051 ** Functions for accessing sqlite3_file methods
   8052 */
   8053 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
   8054 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   8055 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   8056 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   8057 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   8058 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   8059 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   8060 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   8061 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   8062 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   8063 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   8064 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   8065 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   8066 
   8067 /*
   8068 ** Functions for accessing sqlite3_vfs methods
   8069 */
   8070 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   8071 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   8072 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   8073 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   8074 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   8075 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   8076 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   8077 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   8078 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   8079 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   8080 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   8081 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   8082 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
   8083 
   8084 /*
   8085 ** Convenience functions for opening and closing files using
   8086 ** sqlite3_malloc() to obtain space for the file-handle structure.
   8087 */
   8088 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   8089 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
   8090 
   8091 #endif /* _SQLITE_OS_H_ */
   8092 
   8093 /************** End of os.h **************************************************/
   8094 /************** Continuing where we left off in sqliteInt.h ******************/
   8095 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   8096 /************** Begin file mutex.h *******************************************/
   8097 /*
   8098 ** 2007 August 28
   8099 **
   8100 ** The author disclaims copyright to this source code.  In place of
   8101 ** a legal notice, here is a blessing:
   8102 **
   8103 **    May you do good and not evil.
   8104 **    May you find forgiveness for yourself and forgive others.
   8105 **    May you share freely, never taking more than you give.
   8106 **
   8107 *************************************************************************
   8108 **
   8109 ** This file contains the common header for all mutex implementations.
   8110 ** The sqliteInt.h header #includes this file so that it is available
   8111 ** to all source files.  We break it out in an effort to keep the code
   8112 ** better organized.
   8113 **
   8114 ** NOTE:  source files should *not* #include this header file directly.
   8115 ** Source files should #include the sqliteInt.h file and let that file
   8116 ** include this one indirectly.
   8117 */
   8118 
   8119 
   8120 /*
   8121 ** Figure out what version of the code to use.  The choices are
   8122 **
   8123 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   8124 **                             mutexes implemention cannot be overridden
   8125 **                             at start-time.
   8126 **
   8127 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   8128 **                             mutual exclusion is provided.  But this
   8129 **                             implementation can be overridden at
   8130 **                             start-time.
   8131 **
   8132 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   8133 **
   8134 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   8135 **
   8136 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
   8137 */
   8138 #if !SQLITE_THREADSAFE
   8139 # define SQLITE_MUTEX_OMIT
   8140 #endif
   8141 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   8142 #  if SQLITE_OS_UNIX
   8143 #    define SQLITE_MUTEX_PTHREADS
   8144 #  elif SQLITE_OS_WIN
   8145 #    define SQLITE_MUTEX_W32
   8146 #  elif SQLITE_OS_OS2
   8147 #    define SQLITE_MUTEX_OS2
   8148 #  else
   8149 #    define SQLITE_MUTEX_NOOP
   8150 #  endif
   8151 #endif
   8152 
   8153 #ifdef SQLITE_MUTEX_OMIT
   8154 /*
   8155 ** If this is a no-op implementation, implement everything as macros.
   8156 */
   8157 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   8158 #define sqlite3_mutex_free(X)
   8159 #define sqlite3_mutex_enter(X)
   8160 #define sqlite3_mutex_try(X)      SQLITE_OK
   8161 #define sqlite3_mutex_leave(X)
   8162 #define sqlite3_mutex_held(X)     1
   8163 #define sqlite3_mutex_notheld(X)  1
   8164 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   8165 #define sqlite3MutexInit()        SQLITE_OK
   8166 #define sqlite3MutexEnd()
   8167 #endif /* defined(SQLITE_MUTEX_OMIT) */
   8168 
   8169 /************** End of mutex.h ***********************************************/
   8170 /************** Continuing where we left off in sqliteInt.h ******************/
   8171 
   8172 
   8173 /*
   8174 ** Each database file to be accessed by the system is an instance
   8175 ** of the following structure.  There are normally two of these structures
   8176 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   8177 ** aDb[1] is the database file used to hold temporary tables.  Additional
   8178 ** databases may be attached.
   8179 */
   8180 struct Db {
   8181   char *zName;         /* Name of this database */
   8182   Btree *pBt;          /* The B*Tree structure for this database file */
   8183   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
   8184   u8 safety_level;     /* How aggressive at syncing data to disk */
   8185   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   8186 };
   8187 
   8188 /*
   8189 ** An instance of the following structure stores a database schema.
   8190 **
   8191 ** If there are no virtual tables configured in this schema, the
   8192 ** Schema.db variable is set to NULL. After the first virtual table
   8193 ** has been added, it is set to point to the database connection
   8194 ** used to create the connection. Once a virtual table has been
   8195 ** added to the Schema structure and the Schema.db variable populated,
   8196 ** only that database connection may use the Schema to prepare
   8197 ** statements.
   8198 */
   8199 struct Schema {
   8200   int schema_cookie;   /* Database schema version number for this file */
   8201   Hash tblHash;        /* All tables indexed by name */
   8202   Hash idxHash;        /* All (named) indices indexed by name */
   8203   Hash trigHash;       /* All triggers indexed by name */
   8204   Hash fkeyHash;       /* All foreign keys by referenced table name */
   8205   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   8206   u8 file_format;      /* Schema format version for this file */
   8207   u8 enc;              /* Text encoding used by this database */
   8208   u16 flags;           /* Flags associated with this schema */
   8209   int cache_size;      /* Number of pages to use in the cache */
   8210 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8211   sqlite3 *db;         /* "Owner" connection. See comment above */
   8212 #endif
   8213 };
   8214 
   8215 /*
   8216 ** These macros can be used to test, set, or clear bits in the
   8217 ** Db.flags field.
   8218 */
   8219 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
   8220 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
   8221 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
   8222 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
   8223 
   8224 /*
   8225 ** Allowed values for the DB.flags field.
   8226 **
   8227 ** The DB_SchemaLoaded flag is set after the database schema has been
   8228 ** read into internal hash tables.
   8229 **
   8230 ** DB_UnresetViews means that one or more views have column names that
   8231 ** have been filled out.  If the schema changes, these column names might
   8232 ** changes and so the view will need to be reset.
   8233 */
   8234 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   8235 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   8236 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   8237 
   8238 /*
   8239 ** The number of different kinds of things that can be limited
   8240 ** using the sqlite3_limit() interface.
   8241 */
   8242 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
   8243 
   8244 /*
   8245 ** Lookaside malloc is a set of fixed-size buffers that can be used
   8246 ** to satisfy small transient memory allocation requests for objects
   8247 ** associated with a particular database connection.  The use of
   8248 ** lookaside malloc provides a significant performance enhancement
   8249 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   8250 ** SQL statements.
   8251 **
   8252 ** The Lookaside structure holds configuration information about the
   8253 ** lookaside malloc subsystem.  Each available memory allocation in
   8254 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   8255 ** objects.
   8256 **
   8257 ** Lookaside allocations are only allowed for objects that are associated
   8258 ** with a particular database connection.  Hence, schema information cannot
   8259 ** be stored in lookaside because in shared cache mode the schema information
   8260 ** is shared by multiple database connections.  Therefore, while parsing
   8261 ** schema information, the Lookaside.bEnabled flag is cleared so that
   8262 ** lookaside allocations are not used to construct the schema objects.
   8263 */
   8264 struct Lookaside {
   8265   u16 sz;                 /* Size of each buffer in bytes */
   8266   u8 bEnabled;            /* False to disable new lookaside allocations */
   8267   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   8268   int nOut;               /* Number of buffers currently checked out */
   8269   int mxOut;              /* Highwater mark for nOut */
   8270   LookasideSlot *pFree;   /* List of available buffers */
   8271   void *pStart;           /* First byte of available memory space */
   8272   void *pEnd;             /* First byte past end of available space */
   8273 };
   8274 struct LookasideSlot {
   8275   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   8276 };
   8277 
   8278 /*
   8279 ** A hash table for function definitions.
   8280 **
   8281 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   8282 ** Collisions are on the FuncDef.pHash chain.
   8283 */
   8284 struct FuncDefHash {
   8285   FuncDef *a[23];       /* Hash table for functions */
   8286 };
   8287 
   8288 /*
   8289 ** Each database is an instance of the following structure.
   8290 **
   8291 ** The sqlite.lastRowid records the last insert rowid generated by an
   8292 ** insert statement.  Inserts on views do not affect its value.  Each
   8293 ** trigger has its own context, so that lastRowid can be updated inside
   8294 ** triggers as usual.  The previous value will be restored once the trigger
   8295 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
   8296 ** longer (since after version 2.8.12) reset to -1.
   8297 **
   8298 ** The sqlite.nChange does not count changes within triggers and keeps no
   8299 ** context.  It is reset at start of sqlite3_exec.
   8300 ** The sqlite.lsChange represents the number of changes made by the last
   8301 ** insert, update, or delete statement.  It remains constant throughout the
   8302 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
   8303 ** context stack just like lastRowid so that the count of changes
   8304 ** within a trigger is not seen outside the trigger.  Changes to views do not
   8305 ** affect the value of lsChange.
   8306 ** The sqlite.csChange keeps track of the number of current changes (since
   8307 ** the last statement) and is used to update sqlite_lsChange.
   8308 **
   8309 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
   8310 ** store the most recent error code and, if applicable, string. The
   8311 ** internal function sqlite3Error() is used to set these variables
   8312 ** consistently.
   8313 */
   8314 struct sqlite3 {
   8315   sqlite3_vfs *pVfs;            /* OS Interface */
   8316   int nDb;                      /* Number of backends currently in use */
   8317   Db *aDb;                      /* All backends */
   8318   int flags;                    /* Miscellaneous flags. See below */
   8319   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
   8320   int errCode;                  /* Most recent error code (SQLITE_*) */
   8321   int errMask;                  /* & result codes with this before returning */
   8322   u8 autoCommit;                /* The auto-commit flag. */
   8323   u8 temp_store;                /* 1: file 2: memory 0: default */
   8324   u8 mallocFailed;              /* True if we have seen a malloc failure */
   8325   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   8326   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
   8327   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   8328   u8 suppressErr;               /* Do not issue error messages if true */
   8329   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   8330   int nTable;                   /* Number of tables in the database */
   8331   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   8332   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   8333   u32 magic;                    /* Magic number for detect library misuse */
   8334   int nChange;                  /* Value returned by sqlite3_changes() */
   8335   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   8336   sqlite3_mutex *mutex;         /* Connection mutex */
   8337   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   8338   struct sqlite3InitInfo {      /* Information used during initialization */
   8339     int iDb;                    /* When back is being initialized */
   8340     int newTnum;                /* Rootpage of table being initialized */
   8341     u8 busy;                    /* TRUE if currently initializing */
   8342     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   8343   } init;
   8344   int nExtension;               /* Number of loaded extensions */
   8345   void **aExtension;            /* Array of shared library handles */
   8346   struct Vdbe *pVdbe;           /* List of active virtual machines */
   8347   int activeVdbeCnt;            /* Number of VDBEs currently executing */
   8348   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
   8349   void (*xTrace)(void*,const char*);        /* Trace function */
   8350   void *pTraceArg;                          /* Argument to the trace function */
   8351   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   8352   void *pProfileArg;                        /* Argument to profile function */
   8353   void *pCommitArg;                 /* Argument to xCommitCallback() */
   8354   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   8355   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   8356   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   8357   void *pUpdateArg;
   8358   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   8359   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   8360   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   8361   void *pCollNeededArg;
   8362   sqlite3_value *pErr;          /* Most recent error message */
   8363   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
   8364   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
   8365   union {
   8366     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   8367     double notUsed1;            /* Spacer */
   8368   } u1;
   8369   Lookaside lookaside;          /* Lookaside malloc configuration */
   8370 #ifndef SQLITE_OMIT_AUTHORIZATION
   8371   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   8372                                 /* Access authorization function */
   8373   void *pAuthArg;               /* 1st argument to the access auth function */
   8374 #endif
   8375 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   8376   int (*xProgress)(void *);     /* The progress callback */
   8377   void *pProgressArg;           /* Argument to the progress callback */
   8378   int nProgressOps;             /* Number of opcodes for progress callback */
   8379 #endif
   8380 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8381   Hash aModule;                 /* populated by sqlite3_create_module() */
   8382   Table *pVTab;                 /* vtab with active Connect/Create method */
   8383   VTable **aVTrans;             /* Virtual tables with open transactions */
   8384   int nVTrans;                  /* Allocated size of aVTrans */
   8385   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
   8386 #endif
   8387   FuncDefHash aFunc;            /* Hash table of connection functions */
   8388   Hash aCollSeq;                /* All collating sequences */
   8389   BusyHandler busyHandler;      /* Busy callback */
   8390   int busyTimeout;              /* Busy handler timeout, in msec */
   8391   Db aDbStatic[2];              /* Static space for the 2 default backends */
   8392   Savepoint *pSavepoint;        /* List of active savepoints */
   8393   int nSavepoint;               /* Number of non-transaction savepoints */
   8394   int nStatement;               /* Number of nested statement-transactions  */
   8395   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   8396   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   8397 
   8398 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   8399   /* The following variables are all protected by the STATIC_MASTER
   8400   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   8401   **
   8402   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   8403   ** unlock so that it can proceed.
   8404   **
   8405   ** When X.pBlockingConnection==Y, that means that something that X tried
   8406   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   8407   ** held by Y.
   8408   */
   8409   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   8410   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   8411   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   8412   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   8413   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   8414 #endif
   8415 };
   8416 
   8417 /*
   8418 ** A macro to discover the encoding of a database.
   8419 */
   8420 #define ENC(db) ((db)->aDb[0].pSchema->enc)
   8421 
   8422 /*
   8423 ** Possible values for the sqlite3.flags.
   8424 */
   8425 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
   8426 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
   8427 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
   8428 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
   8429 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
   8430                                           /*   DELETE, or UPDATE and return */
   8431                                           /*   the count using a callback. */
   8432 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
   8433                                           /*   result set is empty */
   8434 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
   8435 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
   8436 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
   8437 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
   8438                                           ** accessing read-only databases */
   8439 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
   8440 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
   8441 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
   8442 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
   8443 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
   8444 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
   8445 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
   8446 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
   8447 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
   8448 
   8449 /*
   8450 ** Bits of the sqlite3.flags field that are used by the
   8451 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
   8452 ** These must be the low-order bits of the flags field.
   8453 */
   8454 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
   8455 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
   8456 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
   8457 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
   8458 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
   8459 #define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
   8460 
   8461 /*
   8462 ** Possible values for the sqlite.magic field.
   8463 ** The numbers are obtained at random and have no special meaning, other
   8464 ** than being distinct from one another.
   8465 */
   8466 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   8467 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   8468 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   8469 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   8470 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   8471 
   8472 /*
   8473 ** Each SQL function is defined by an instance of the following
   8474 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
   8475 ** hash table.  When multiple functions have the same name, the hash table
   8476 ** points to a linked list of these structures.
   8477 */
   8478 struct FuncDef {
   8479   i16 nArg;            /* Number of arguments.  -1 means unlimited */
   8480   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
   8481   u8 flags;            /* Some combination of SQLITE_FUNC_* */
   8482   void *pUserData;     /* User data parameter */
   8483   FuncDef *pNext;      /* Next function with same name */
   8484   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
   8485   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
   8486   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
   8487   char *zName;         /* SQL name of the function. */
   8488   FuncDef *pHash;      /* Next with a different name but the same hash */
   8489 };
   8490 
   8491 /*
   8492 ** Possible values for FuncDef.flags
   8493 */
   8494 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
   8495 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
   8496 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
   8497 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
   8498 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
   8499 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
   8500 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
   8501 
   8502 /*
   8503 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   8504 ** used to create the initializers for the FuncDef structures.
   8505 **
   8506 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   8507 **     Used to create a scalar function definition of a function zName
   8508 **     implemented by C function xFunc that accepts nArg arguments. The
   8509 **     value passed as iArg is cast to a (void*) and made available
   8510 **     as the user-data (sqlite3_user_data()) for the function. If
   8511 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   8512 **
   8513 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   8514 **     Used to create an aggregate function definition implemented by
   8515 **     the C functions xStep and xFinal. The first four parameters
   8516 **     are interpreted in the same way as the first 4 parameters to
   8517 **     FUNCTION().
   8518 **
   8519 **   LIKEFUNC(zName, nArg, pArg, flags)
   8520 **     Used to create a scalar function definition of a function zName
   8521 **     that accepts nArg arguments and is implemented by a call to C
   8522 **     function likeFunc. Argument pArg is cast to a (void *) and made
   8523 **     available as the function user-data (sqlite3_user_data()). The
   8524 **     FuncDef.flags variable is set to the value passed as the flags
   8525 **     parameter.
   8526 */
   8527 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   8528   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   8529    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
   8530 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   8531   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   8532    pArg, 0, xFunc, 0, 0, #zName, 0}
   8533 #define LIKEFUNC(zName, nArg, arg, flags) \
   8534   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
   8535 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   8536   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
   8537    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
   8538 
   8539 /*
   8540 ** All current savepoints are stored in a linked list starting at
   8541 ** sqlite3.pSavepoint. The first element in the list is the most recently
   8542 ** opened savepoint. Savepoints are added to the list by the vdbe
   8543 ** OP_Savepoint instruction.
   8544 */
   8545 struct Savepoint {
   8546   char *zName;                        /* Savepoint name (nul-terminated) */
   8547   i64 nDeferredCons;                  /* Number of deferred fk violations */
   8548   Savepoint *pNext;                   /* Parent savepoint (if any) */
   8549 };
   8550 
   8551 /*
   8552 ** The following are used as the second parameter to sqlite3Savepoint(),
   8553 ** and as the P1 argument to the OP_Savepoint instruction.
   8554 */
   8555 #define SAVEPOINT_BEGIN      0
   8556 #define SAVEPOINT_RELEASE    1
   8557 #define SAVEPOINT_ROLLBACK   2
   8558 
   8559 
   8560 /*
   8561 ** Each SQLite module (virtual table definition) is defined by an
   8562 ** instance of the following structure, stored in the sqlite3.aModule
   8563 ** hash table.
   8564 */
   8565 struct Module {
   8566   const sqlite3_module *pModule;       /* Callback pointers */
   8567   const char *zName;                   /* Name passed to create_module() */
   8568   void *pAux;                          /* pAux passed to create_module() */
   8569   void (*xDestroy)(void *);            /* Module destructor function */
   8570 };
   8571 
   8572 /*
   8573 ** information about each column of an SQL table is held in an instance
   8574 ** of this structure.
   8575 */
   8576 struct Column {
   8577   char *zName;     /* Name of this column */
   8578   Expr *pDflt;     /* Default value of this column */
   8579   char *zDflt;     /* Original text of the default value */
   8580   char *zType;     /* Data type for this column */
   8581   char *zColl;     /* Collating sequence.  If NULL, use the default */
   8582   u8 notNull;      /* True if there is a NOT NULL constraint */
   8583   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
   8584   char affinity;   /* One of the SQLITE_AFF_... values */
   8585 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8586   u8 isHidden;     /* True if this column is 'hidden' */
   8587 #endif
   8588 };
   8589 
   8590 /*
   8591 ** A "Collating Sequence" is defined by an instance of the following
   8592 ** structure. Conceptually, a collating sequence consists of a name and
   8593 ** a comparison routine that defines the order of that sequence.
   8594 **
   8595 ** There may two separate implementations of the collation function, one
   8596 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
   8597 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
   8598 ** native byte order. When a collation sequence is invoked, SQLite selects
   8599 ** the version that will require the least expensive encoding
   8600 ** translations, if any.
   8601 **
   8602 ** The CollSeq.pUser member variable is an extra parameter that passed in
   8603 ** as the first argument to the UTF-8 comparison function, xCmp.
   8604 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
   8605 ** xCmp16.
   8606 **
   8607 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
   8608 ** collating sequence is undefined.  Indices built on an undefined
   8609 ** collating sequence may not be read or written.
   8610 */
   8611 struct CollSeq {
   8612   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   8613   u8 enc;               /* Text encoding handled by xCmp() */
   8614   u8 type;              /* One of the SQLITE_COLL_... values below */
   8615   void *pUser;          /* First argument to xCmp() */
   8616   int (*xCmp)(void*,int, const void*, int, const void*);
   8617   void (*xDel)(void*);  /* Destructor for pUser */
   8618 };
   8619 
   8620 /*
   8621 ** Allowed values of CollSeq.type:
   8622 */
   8623 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
   8624 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
   8625 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
   8626 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
   8627 
   8628 /*
   8629 ** A sort order can be either ASC or DESC.
   8630 */
   8631 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   8632 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   8633 
   8634 /*
   8635 ** Column affinity types.
   8636 **
   8637 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   8638 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   8639 ** the speed a little by numbering the values consecutively.
   8640 **
   8641 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
   8642 ** when multiple affinity types are concatenated into a string and
   8643 ** used as the P4 operand, they will be more readable.
   8644 **
   8645 ** Note also that the numeric types are grouped together so that testing
   8646 ** for a numeric type is a single comparison.
   8647 */
   8648 #define SQLITE_AFF_TEXT     'a'
   8649 #define SQLITE_AFF_NONE     'b'
   8650 #define SQLITE_AFF_NUMERIC  'c'
   8651 #define SQLITE_AFF_INTEGER  'd'
   8652 #define SQLITE_AFF_REAL     'e'
   8653 
   8654 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   8655 
   8656 /*
   8657 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   8658 ** affinity value.
   8659 */
   8660 #define SQLITE_AFF_MASK     0x67
   8661 
   8662 /*
   8663 ** Additional bit values that can be ORed with an affinity without
   8664 ** changing the affinity.
   8665 */
   8666 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
   8667 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
   8668 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   8669 
   8670 /*
   8671 ** An object of this type is created for each virtual table present in
   8672 ** the database schema.
   8673 **
   8674 ** If the database schema is shared, then there is one instance of this
   8675 ** structure for each database connection (sqlite3*) that uses the shared
   8676 ** schema. This is because each database connection requires its own unique
   8677 ** instance of the sqlite3_vtab* handle used to access the virtual table
   8678 ** implementation. sqlite3_vtab* handles can not be shared between
   8679 ** database connections, even when the rest of the in-memory database
   8680 ** schema is shared, as the implementation often stores the database
   8681 ** connection handle passed to it via the xConnect() or xCreate() method
   8682 ** during initialization internally. This database connection handle may
   8683 ** then used by the virtual table implementation to access real tables
   8684 ** within the database. So that they appear as part of the callers
   8685 ** transaction, these accesses need to be made via the same database
   8686 ** connection as that used to execute SQL operations on the virtual table.
   8687 **
   8688 ** All VTable objects that correspond to a single table in a shared
   8689 ** database schema are initially stored in a linked-list pointed to by
   8690 ** the Table.pVTable member variable of the corresponding Table object.
   8691 ** When an sqlite3_prepare() operation is required to access the virtual
   8692 ** table, it searches the list for the VTable that corresponds to the
   8693 ** database connection doing the preparing so as to use the correct
   8694 ** sqlite3_vtab* handle in the compiled query.
   8695 **
   8696 ** When an in-memory Table object is deleted (for example when the
   8697 ** schema is being reloaded for some reason), the VTable objects are not
   8698 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   8699 ** immediately. Instead, they are moved from the Table.pVTable list to
   8700 ** another linked list headed by the sqlite3.pDisconnect member of the
   8701 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   8702 ** next time a statement is prepared using said sqlite3*. This is done
   8703 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   8704 ** Refer to comments above function sqlite3VtabUnlockList() for an
   8705 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   8706 ** list without holding the corresponding sqlite3.mutex mutex.
   8707 **
   8708 ** The memory for objects of this type is always allocated by
   8709 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   8710 ** the first argument.
   8711 */
   8712 struct VTable {
   8713   sqlite3 *db;              /* Database connection associated with this table */
   8714   Module *pMod;             /* Pointer to module implementation */
   8715   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   8716   int nRef;                 /* Number of pointers to this structure */
   8717   VTable *pNext;            /* Next in linked list (see above) */
   8718 };
   8719 
   8720 /*
   8721 ** Each SQL table is represented in memory by an instance of the
   8722 ** following structure.
   8723 **
   8724 ** Table.zName is the name of the table.  The case of the original
   8725 ** CREATE TABLE statement is stored, but case is not significant for
   8726 ** comparisons.
   8727 **
   8728 ** Table.nCol is the number of columns in this table.  Table.aCol is a
   8729 ** pointer to an array of Column structures, one for each column.
   8730 **
   8731 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
   8732 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
   8733 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
   8734 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
   8735 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
   8736 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
   8737 ** the table has any PRIMARY KEY, INTEGER or otherwise.
   8738 **
   8739 ** Table.tnum is the page number for the root BTree page of the table in the
   8740 ** database file.  If Table.iDb is the index of the database table backend
   8741 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
   8742 ** holds temporary tables and indices.  If TF_Ephemeral is set
   8743 ** then the table is stored in a file that is automatically deleted
   8744 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
   8745 ** refers VDBE cursor number that holds the table open, not to the root
   8746 ** page number.  Transient tables are used to hold the results of a
   8747 ** sub-query that appears instead of a real table name in the FROM clause
   8748 ** of a SELECT statement.
   8749 */
   8750 struct Table {
   8751   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
   8752   char *zName;         /* Name of the table or view */
   8753   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
   8754   int nCol;            /* Number of columns in this table */
   8755   Column *aCol;        /* Information about each column */
   8756   Index *pIndex;       /* List of SQL indexes on this table. */
   8757   int tnum;            /* Root BTree node for this table (see note above) */
   8758   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   8759   u16 nRef;            /* Number of pointers to this Table */
   8760   u8 tabFlags;         /* Mask of TF_* values */
   8761   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   8762   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   8763   char *zColAff;       /* String defining the affinity of each column */
   8764 #ifndef SQLITE_OMIT_CHECK
   8765   Expr *pCheck;        /* The AND of all CHECK constraints */
   8766 #endif
   8767 #ifndef SQLITE_OMIT_ALTERTABLE
   8768   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   8769 #endif
   8770 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8771   VTable *pVTable;     /* List of VTable objects. */
   8772   int nModuleArg;      /* Number of arguments to the module */
   8773   char **azModuleArg;  /* Text of all module args. [0] is module name */
   8774 #endif
   8775   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   8776   Schema *pSchema;     /* Schema that contains this table */
   8777   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   8778 };
   8779 
   8780 /*
   8781 ** Allowed values for Tabe.tabFlags.
   8782 */
   8783 #define TF_Readonly        0x01    /* Read-only system table */
   8784 #define TF_Ephemeral       0x02    /* An ephemeral table */
   8785 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
   8786 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
   8787 #define TF_Virtual         0x10    /* Is a virtual table */
   8788 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
   8789 
   8790 
   8791 
   8792 /*
   8793 ** Test to see whether or not a table is a virtual table.  This is
   8794 ** done as a macro so that it will be optimized out when virtual
   8795 ** table support is omitted from the build.
   8796 */
   8797 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8798 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
   8799 #  define IsHiddenColumn(X) ((X)->isHidden)
   8800 #else
   8801 #  define IsVirtual(X)      0
   8802 #  define IsHiddenColumn(X) 0
   8803 #endif
   8804 
   8805 /*
   8806 ** Each foreign key constraint is an instance of the following structure.
   8807 **
   8808 ** A foreign key is associated with two tables.  The "from" table is
   8809 ** the table that contains the REFERENCES clause that creates the foreign
   8810 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   8811 ** Consider this example:
   8812 **
   8813 **     CREATE TABLE ex1(
   8814 **       a INTEGER PRIMARY KEY,
   8815 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   8816 **     );
   8817 **
   8818 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   8819 **
   8820 ** Each REFERENCES clause generates an instance of the following structure
   8821 ** which is attached to the from-table.  The to-table need not exist when
   8822 ** the from-table is created.  The existence of the to-table is not checked.
   8823 */
   8824 struct FKey {
   8825   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   8826   FKey *pNextFrom;  /* Next foreign key in pFrom */
   8827   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   8828   FKey *pNextTo;    /* Next foreign key on table named zTo */
   8829   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
   8830   int nCol;         /* Number of columns in this key */
   8831   /* EV: R-30323-21917 */
   8832   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
   8833   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
   8834   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
   8835   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
   8836     int iFrom;         /* Index of column in pFrom */
   8837     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
   8838   } aCol[1];        /* One entry for each of nCol column s */
   8839 };
   8840 
   8841 /*
   8842 ** SQLite supports many different ways to resolve a constraint
   8843 ** error.  ROLLBACK processing means that a constraint violation
   8844 ** causes the operation in process to fail and for the current transaction
   8845 ** to be rolled back.  ABORT processing means the operation in process
   8846 ** fails and any prior changes from that one operation are backed out,
   8847 ** but the transaction is not rolled back.  FAIL processing means that
   8848 ** the operation in progress stops and returns an error code.  But prior
   8849 ** changes due to the same operation are not backed out and no rollback
   8850 ** occurs.  IGNORE means that the particular row that caused the constraint
   8851 ** error is not inserted or updated.  Processing continues and no error
   8852 ** is returned.  REPLACE means that preexisting database rows that caused
   8853 ** a UNIQUE constraint violation are removed so that the new insert or
   8854 ** update can proceed.  Processing continues and no error is reported.
   8855 **
   8856 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   8857 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   8858 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   8859 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   8860 ** referenced table row is propagated into the row that holds the
   8861 ** foreign key.
   8862 **
   8863 ** The following symbolic values are used to record which type
   8864 ** of action to take.
   8865 */
   8866 #define OE_None     0   /* There is no constraint to check */
   8867 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   8868 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   8869 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   8870 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   8871 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   8872 
   8873 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   8874 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   8875 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   8876 #define OE_Cascade  9   /* Cascade the changes */
   8877 
   8878 #define OE_Default  99  /* Do whatever the default action is */
   8879 
   8880 
   8881 /*
   8882 ** An instance of the following structure is passed as the first
   8883 ** argument to sqlite3VdbeKeyCompare and is used to control the
   8884 ** comparison of the two index keys.
   8885 */
   8886 struct KeyInfo {
   8887   sqlite3 *db;        /* The database connection */
   8888   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
   8889   u16 nField;         /* Number of entries in aColl[] */
   8890   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
   8891   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   8892 };
   8893 
   8894 /*
   8895 ** An instance of the following structure holds information about a
   8896 ** single index record that has already been parsed out into individual
   8897 ** values.
   8898 **
   8899 ** A record is an object that contains one or more fields of data.
   8900 ** Records are used to store the content of a table row and to store
   8901 ** the key of an index.  A blob encoding of a record is created by
   8902 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   8903 ** OP_Column opcode.
   8904 **
   8905 ** This structure holds a record that has already been disassembled
   8906 ** into its constituent fields.
   8907 */
   8908 struct UnpackedRecord {
   8909   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   8910   u16 nField;         /* Number of entries in apMem[] */
   8911   u16 flags;          /* Boolean settings.  UNPACKED_... below */
   8912   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
   8913   Mem *aMem;          /* Values */
   8914 };
   8915 
   8916 /*
   8917 ** Allowed values of UnpackedRecord.flags
   8918 */
   8919 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
   8920 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
   8921 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
   8922 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
   8923 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
   8924 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
   8925 
   8926 /*
   8927 ** Each SQL index is represented in memory by an
   8928 ** instance of the following structure.
   8929 **
   8930 ** The columns of the table that are to be indexed are described
   8931 ** by the aiColumn[] field of this structure.  For example, suppose
   8932 ** we have the following table and index:
   8933 **
   8934 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   8935 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   8936 **
   8937 ** In the Table structure describing Ex1, nCol==3 because there are
   8938 ** three columns in the table.  In the Index structure describing
   8939 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   8940 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   8941 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   8942 ** The second column to be indexed (c1) has an index of 0 in
   8943 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   8944 **
   8945 ** The Index.onError field determines whether or not the indexed columns
   8946 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   8947 ** it means this is not a unique index.  Otherwise it is a unique index
   8948 ** and the value of Index.onError indicate the which conflict resolution
   8949 ** algorithm to employ whenever an attempt is made to insert a non-unique
   8950 ** element.
   8951 */
   8952 struct Index {
   8953   char *zName;     /* Name of this index */
   8954   int nColumn;     /* Number of columns in the table used by this index */
   8955   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
   8956   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
   8957   Table *pTable;   /* The SQL table being indexed */
   8958   int tnum;        /* Page containing root of this index in database file */
   8959   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   8960   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
   8961   char *zColAff;   /* String defining the affinity of each column */
   8962   Index *pNext;    /* The next index associated with the same table */
   8963   Schema *pSchema; /* Schema containing this index */
   8964   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
   8965   char **azColl;   /* Array of collation sequence names for index */
   8966   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
   8967 };
   8968 
   8969 /*
   8970 ** Each sample stored in the sqlite_stat2 table is represented in memory
   8971 ** using a structure of this type.
   8972 */
   8973 struct IndexSample {
   8974   union {
   8975     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
   8976     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
   8977   } u;
   8978   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
   8979   u8 nByte;         /* Size in byte of text or blob. */
   8980 };
   8981 
   8982 /*
   8983 ** Each token coming out of the lexer is an instance of
   8984 ** this structure.  Tokens are also used as part of an expression.
   8985 **
   8986 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   8987 ** may contain random values.  Do not make any assumptions about Token.dyn
   8988 ** and Token.n when Token.z==0.
   8989 */
   8990 struct Token {
   8991   const char *z;     /* Text of the token.  Not NULL-terminated! */
   8992   unsigned int n;    /* Number of characters in this token */
   8993 };
   8994 
   8995 /*
   8996 ** An instance of this structure contains information needed to generate
   8997 ** code for a SELECT that contains aggregate functions.
   8998 **
   8999 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   9000 ** pointer to this structure.  The Expr.iColumn field is the index in
   9001 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   9002 ** code for that node.
   9003 **
   9004 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   9005 ** original Select structure that describes the SELECT statement.  These
   9006 ** fields do not need to be freed when deallocating the AggInfo structure.
   9007 */
   9008 struct AggInfo {
   9009   u8 directMode;          /* Direct rendering mode means take data directly
   9010                           ** from source tables rather than from accumulators */
   9011   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   9012                           ** than the source table */
   9013   int sortingIdx;         /* Cursor number of the sorting index */
   9014   ExprList *pGroupBy;     /* The group by clause */
   9015   int nSortingColumn;     /* Number of columns in the sorting index */
   9016   struct AggInfo_col {    /* For each column used in source tables */
   9017     Table *pTab;             /* Source table */
   9018     int iTable;              /* Cursor number of the source table */
   9019     int iColumn;             /* Column number within the source table */
   9020     int iSorterColumn;       /* Column number in the sorting index */
   9021     int iMem;                /* Memory location that acts as accumulator */
   9022     Expr *pExpr;             /* The original expression */
   9023   } *aCol;
   9024   int nColumn;            /* Number of used entries in aCol[] */
   9025   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
   9026   int nAccumulator;       /* Number of columns that show through to the output.
   9027                           ** Additional columns are used only as parameters to
   9028                           ** aggregate functions */
   9029   struct AggInfo_func {   /* For each aggregate function */
   9030     Expr *pExpr;             /* Expression encoding the function */
   9031     FuncDef *pFunc;          /* The aggregate function implementation */
   9032     int iMem;                /* Memory location that acts as accumulator */
   9033     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   9034   } *aFunc;
   9035   int nFunc;              /* Number of entries in aFunc[] */
   9036   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
   9037 };
   9038 
   9039 /*
   9040 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   9041 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   9042 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   9043 ** it uses less memory in the Expr object, which is a big memory user
   9044 ** in systems with lots of prepared statements.  And few applications
   9045 ** need more than about 10 or 20 variables.  But some extreme users want
   9046 ** to have prepared statements with over 32767 variables, and for them
   9047 ** the option is available (at compile-time).
   9048 */
   9049 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   9050 typedef i16 ynVar;
   9051 #else
   9052 typedef int ynVar;
   9053 #endif
   9054 
   9055 /*
   9056 ** Each node of an expression in the parse tree is an instance
   9057 ** of this structure.
   9058 **
   9059 ** Expr.op is the opcode. The integer parser token codes are reused
   9060 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   9061 ** code representing the ">=" operator. This same integer code is reused
   9062 ** to represent the greater-than-or-equal-to operator in the expression
   9063 ** tree.
   9064 **
   9065 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   9066 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   9067 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   9068 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   9069 ** then Expr.token contains the name of the function.
   9070 **
   9071 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   9072 ** binary operator. Either or both may be NULL.
   9073 **
   9074 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   9075 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   9076 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   9077 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   9078 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   9079 ** valid.
   9080 **
   9081 ** An expression of the form ID or ID.ID refers to a column in a table.
   9082 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   9083 ** the integer cursor number of a VDBE cursor pointing to that table and
   9084 ** Expr.iColumn is the column number for the specific column.  If the
   9085 ** expression is used as a result in an aggregate SELECT, then the
   9086 ** value is also stored in the Expr.iAgg column in the aggregate so that
   9087 ** it can be accessed after all aggregates are computed.
   9088 **
   9089 ** If the expression is an unbound variable marker (a question mark
   9090 ** character '?' in the original SQL) then the Expr.iTable holds the index
   9091 ** number for that variable.
   9092 **
   9093 ** If the expression is a subquery then Expr.iColumn holds an integer
   9094 ** register number containing the result of the subquery.  If the
   9095 ** subquery gives a constant result, then iTable is -1.  If the subquery
   9096 ** gives a different answer at different times during statement processing
   9097 ** then iTable is the address of a subroutine that computes the subquery.
   9098 **
   9099 ** If the Expr is of type OP_Column, and the table it is selecting from
   9100 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   9101 ** corresponding table definition.
   9102 **
   9103 ** ALLOCATION NOTES:
   9104 **
   9105 ** Expr objects can use a lot of memory space in database schema.  To
   9106 ** help reduce memory requirements, sometimes an Expr object will be
   9107 ** truncated.  And to reduce the number of memory allocations, sometimes
   9108 ** two or more Expr objects will be stored in a single memory allocation,
   9109 ** together with Expr.zToken strings.
   9110 **
   9111 ** If the EP_Reduced and EP_TokenOnly flags are set when
   9112 ** an Expr object is truncated.  When EP_Reduced is set, then all
   9113 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   9114 ** are contained within the same memory allocation.  Note, however, that
   9115 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   9116 ** allocated, regardless of whether or not EP_Reduced is set.
   9117 */
   9118 struct Expr {
   9119   u8 op;                 /* Operation performed by this node */
   9120   char affinity;         /* The affinity of the column or 0 if not a column */
   9121   u16 flags;             /* Various flags.  EP_* See below */
   9122   union {
   9123     char *zToken;          /* Token value. Zero terminated and dequoted */
   9124     int iValue;            /* Integer value if EP_IntValue */
   9125   } u;
   9126 
   9127   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   9128   ** space is allocated for the fields below this point. An attempt to
   9129   ** access them will result in a segfault or malfunction.
   9130   *********************************************************************/
   9131 
   9132   Expr *pLeft;           /* Left subnode */
   9133   Expr *pRight;          /* Right subnode */
   9134   union {
   9135     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
   9136     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
   9137   } x;
   9138   CollSeq *pColl;        /* The collation type of the column or 0 */
   9139 
   9140   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   9141   ** space is allocated for the fields below this point. An attempt to
   9142   ** access them will result in a segfault or malfunction.
   9143   *********************************************************************/
   9144 
   9145   int iTable;            /* TK_COLUMN: cursor number of table holding column
   9146                          ** TK_REGISTER: register number
   9147                          ** TK_TRIGGER: 1 -> new, 0 -> old */
   9148   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   9149                          ** TK_VARIABLE: variable number (always >= 1). */
   9150   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   9151   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   9152   u8 flags2;             /* Second set of flags.  EP2_... */
   9153   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
   9154   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   9155   Table *pTab;           /* Table for TK_COLUMN expressions. */
   9156 #if SQLITE_MAX_EXPR_DEPTH>0
   9157   int nHeight;           /* Height of the tree headed by this node */
   9158 #endif
   9159 };
   9160 
   9161 /*
   9162 ** The following are the meanings of bits in the Expr.flags field.
   9163 */
   9164 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
   9165 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
   9166 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
   9167 #define EP_Error      0x0008  /* Expression contains one or more errors */
   9168 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
   9169 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
   9170 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
   9171 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
   9172 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
   9173 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
   9174 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
   9175 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
   9176 
   9177 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
   9178 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
   9179 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
   9180 
   9181 /*
   9182 ** The following are the meanings of bits in the Expr.flags2 field.
   9183 */
   9184 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
   9185 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
   9186 
   9187 /*
   9188 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
   9189 ** flag on an expression structure.  This flag is used for VV&A only.  The
   9190 ** routine is implemented as a macro that only works when in debugging mode,
   9191 ** so as not to burden production code.
   9192 */
   9193 #ifdef SQLITE_DEBUG
   9194 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
   9195 #else
   9196 # define ExprSetIrreducible(X)
   9197 #endif
   9198 
   9199 /*
   9200 ** These macros can be used to test, set, or clear bits in the
   9201 ** Expr.flags field.
   9202 */
   9203 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
   9204 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
   9205 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   9206 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   9207 
   9208 /*
   9209 ** Macros to determine the number of bytes required by a normal Expr
   9210 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   9211 ** and an Expr struct with the EP_TokenOnly flag set.
   9212 */
   9213 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   9214 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   9215 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   9216 
   9217 /*
   9218 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   9219 ** above sqlite3ExprDup() for details.
   9220 */
   9221 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   9222 
   9223 /*
   9224 ** A list of expressions.  Each expression may optionally have a
   9225 ** name.  An expr/name combination can be used in several ways, such
   9226 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   9227 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   9228 ** also be used as the argument to a function, in which case the a.zName
   9229 ** field is not used.
   9230 */
   9231 struct ExprList {
   9232   int nExpr;             /* Number of expressions on the list */
   9233   int nAlloc;            /* Number of entries allocated below */
   9234   int iECursor;          /* VDBE Cursor associated with this ExprList */
   9235   struct ExprList_item {
   9236     Expr *pExpr;           /* The list of expressions */
   9237     char *zName;           /* Token associated with this expression */
   9238     char *zSpan;           /* Original text of the expression */
   9239     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
   9240     u8 done;               /* A flag to indicate when processing is finished */
   9241     u16 iCol;              /* For ORDER BY, column number in result set */
   9242     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
   9243   } *a;                  /* One entry for each expression */
   9244 };
   9245 
   9246 /*
   9247 ** An instance of this structure is used by the parser to record both
   9248 ** the parse tree for an expression and the span of input text for an
   9249 ** expression.
   9250 */
   9251 struct ExprSpan {
   9252   Expr *pExpr;          /* The expression parse tree */
   9253   const char *zStart;   /* First character of input text */
   9254   const char *zEnd;     /* One character past the end of input text */
   9255 };
   9256 
   9257 /*
   9258 ** An instance of this structure can hold a simple list of identifiers,
   9259 ** such as the list "a,b,c" in the following statements:
   9260 **
   9261 **      INSERT INTO t(a,b,c) VALUES ...;
   9262 **      CREATE INDEX idx ON t(a,b,c);
   9263 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   9264 **
   9265 ** The IdList.a.idx field is used when the IdList represents the list of
   9266 ** column names after a table name in an INSERT statement.  In the statement
   9267 **
   9268 **     INSERT INTO t(a,b,c) ...
   9269 **
   9270 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   9271 */
   9272 struct IdList {
   9273   struct IdList_item {
   9274     char *zName;      /* Name of the identifier */
   9275     int idx;          /* Index in some Table.aCol[] of a column named zName */
   9276   } *a;
   9277   int nId;         /* Number of identifiers on the list */
   9278   int nAlloc;      /* Number of entries allocated for a[] below */
   9279 };
   9280 
   9281 /*
   9282 ** The bitmask datatype defined below is used for various optimizations.
   9283 **
   9284 ** Changing this from a 64-bit to a 32-bit type limits the number of
   9285 ** tables in a join to 32 instead of 64.  But it also reduces the size
   9286 ** of the library by 738 bytes on ix86.
   9287 */
   9288 typedef u64 Bitmask;
   9289 
   9290 /*
   9291 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   9292 */
   9293 #define BMS  ((int)(sizeof(Bitmask)*8))
   9294 
   9295 /*
   9296 ** The following structure describes the FROM clause of a SELECT statement.
   9297 ** Each table or subquery in the FROM clause is a separate element of
   9298 ** the SrcList.a[] array.
   9299 **
   9300 ** With the addition of multiple database support, the following structure
   9301 ** can also be used to describe a particular table such as the table that
   9302 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   9303 ** such a table must be a simple name: ID.  But in SQLite, the table can
   9304 ** now be identified by a database name, a dot, then the table name: ID.ID.
   9305 **
   9306 ** The jointype starts out showing the join type between the current table
   9307 ** and the next table on the list.  The parser builds the list this way.
   9308 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   9309 ** jointype expresses the join between the table and the previous table.
   9310 */
   9311 struct SrcList {
   9312   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
   9313   i16 nAlloc;      /* Number of entries allocated in a[] below */
   9314   struct SrcList_item {
   9315     char *zDatabase;  /* Name of database holding this table */
   9316     char *zName;      /* Name of the table */
   9317     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   9318     Table *pTab;      /* An SQL table corresponding to zName */
   9319     Select *pSelect;  /* A SELECT statement used in place of a table name */
   9320     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
   9321     u8 jointype;      /* Type of join between this able and the previous */
   9322     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
   9323     int iCursor;      /* The VDBE cursor number used to access this table */
   9324     Expr *pOn;        /* The ON clause of a join */
   9325     IdList *pUsing;   /* The USING clause of a join */
   9326     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   9327     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
   9328     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
   9329   } a[1];             /* One entry for each identifier on the list */
   9330 };
   9331 
   9332 /*
   9333 ** Permitted values of the SrcList.a.jointype field
   9334 */
   9335 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   9336 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   9337 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   9338 #define JT_LEFT      0x0008    /* Left outer join */
   9339 #define JT_RIGHT     0x0010    /* Right outer join */
   9340 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   9341 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   9342 
   9343 
   9344 /*
   9345 ** A WherePlan object holds information that describes a lookup
   9346 ** strategy.
   9347 **
   9348 ** This object is intended to be opaque outside of the where.c module.
   9349 ** It is included here only so that that compiler will know how big it
   9350 ** is.  None of the fields in this object should be used outside of
   9351 ** the where.c module.
   9352 **
   9353 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
   9354 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
   9355 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
   9356 ** case that more than one of these conditions is true.
   9357 */
   9358 struct WherePlan {
   9359   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
   9360   u32 nEq;                       /* Number of == constraints */
   9361   union {
   9362     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
   9363     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
   9364     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
   9365   } u;
   9366 };
   9367 
   9368 /*
   9369 ** For each nested loop in a WHERE clause implementation, the WhereInfo
   9370 ** structure contains a single instance of this structure.  This structure
   9371 ** is intended to be private the the where.c module and should not be
   9372 ** access or modified by other modules.
   9373 **
   9374 ** The pIdxInfo field is used to help pick the best index on a
   9375 ** virtual table.  The pIdxInfo pointer contains indexing
   9376 ** information for the i-th table in the FROM clause before reordering.
   9377 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
   9378 ** All other information in the i-th WhereLevel object for the i-th table
   9379 ** after FROM clause ordering.
   9380 */
   9381 struct WhereLevel {
   9382   WherePlan plan;       /* query plan for this element of the FROM clause */
   9383   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   9384   int iTabCur;          /* The VDBE cursor used to access the table */
   9385   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   9386   int addrBrk;          /* Jump here to break out of the loop */
   9387   int addrNxt;          /* Jump here to start the next IN combination */
   9388   int addrCont;         /* Jump here to continue with the next loop cycle */
   9389   int addrFirst;        /* First instruction of interior of the loop */
   9390   u8 iFrom;             /* Which entry in the FROM clause */
   9391   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
   9392   int p1, p2;           /* Operands of the opcode used to ends the loop */
   9393   union {               /* Information that depends on plan.wsFlags */
   9394     struct {
   9395       int nIn;              /* Number of entries in aInLoop[] */
   9396       struct InLoop {
   9397         int iCur;              /* The VDBE cursor used by this IN operator */
   9398         int addrInTop;         /* Top of the IN loop */
   9399       } *aInLoop;           /* Information about each nested IN operator */
   9400     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
   9401   } u;
   9402 
   9403   /* The following field is really not part of the current level.  But
   9404   ** we need a place to cache virtual table index information for each
   9405   ** virtual table in the FROM clause and the WhereLevel structure is
   9406   ** a convenient place since there is one WhereLevel for each FROM clause
   9407   ** element.
   9408   */
   9409   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
   9410 };
   9411 
   9412 /*
   9413 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   9414 ** and the WhereInfo.wctrlFlags member.
   9415 */
   9416 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   9417 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   9418 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   9419 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   9420 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
   9421 #define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
   9422 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
   9423 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
   9424 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
   9425 
   9426 /*
   9427 ** The WHERE clause processing routine has two halves.  The
   9428 ** first part does the start of the WHERE loop and the second
   9429 ** half does the tail of the WHERE loop.  An instance of
   9430 ** this structure is returned by the first half and passed
   9431 ** into the second half to give some continuity.
   9432 */
   9433 struct WhereInfo {
   9434   Parse *pParse;       /* Parsing and code generating context */
   9435   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
   9436   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
   9437   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
   9438   SrcList *pTabList;             /* List of tables in the join */
   9439   int iTop;                      /* The very beginning of the WHERE loop */
   9440   int iContinue;                 /* Jump here to continue with next record */
   9441   int iBreak;                    /* Jump here to break out of the loop */
   9442   int nLevel;                    /* Number of nested loop */
   9443   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
   9444   WhereLevel a[1];               /* Information about each nest loop in WHERE */
   9445 };
   9446 
   9447 /*
   9448 ** A NameContext defines a context in which to resolve table and column
   9449 ** names.  The context consists of a list of tables (the pSrcList) field and
   9450 ** a list of named expression (pEList).  The named expression list may
   9451 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   9452 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   9453 ** pEList corresponds to the result set of a SELECT and is NULL for
   9454 ** other statements.
   9455 **
   9456 ** NameContexts can be nested.  When resolving names, the inner-most
   9457 ** context is searched first.  If no match is found, the next outer
   9458 ** context is checked.  If there is still no match, the next context
   9459 ** is checked.  This process continues until either a match is found
   9460 ** or all contexts are check.  When a match is found, the nRef member of
   9461 ** the context containing the match is incremented.
   9462 **
   9463 ** Each subquery gets a new NameContext.  The pNext field points to the
   9464 ** NameContext in the parent query.  Thus the process of scanning the
   9465 ** NameContext list corresponds to searching through successively outer
   9466 ** subqueries looking for a match.
   9467 */
   9468 struct NameContext {
   9469   Parse *pParse;       /* The parser */
   9470   SrcList *pSrcList;   /* One or more tables used to resolve names */
   9471   ExprList *pEList;    /* Optional list of named expressions */
   9472   int nRef;            /* Number of names resolved by this context */
   9473   int nErr;            /* Number of errors encountered while resolving names */
   9474   u8 allowAgg;         /* Aggregate functions allowed here */
   9475   u8 hasAgg;           /* True if aggregates are seen */
   9476   u8 isCheck;          /* True if resolving names in a CHECK constraint */
   9477   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
   9478   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   9479   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   9480 };
   9481 
   9482 /*
   9483 ** An instance of the following structure contains all information
   9484 ** needed to generate code for a single SELECT statement.
   9485 **
   9486 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   9487 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   9488 ** limit and nOffset to the value of the offset (or 0 if there is not
   9489 ** offset).  But later on, nLimit and nOffset become the memory locations
   9490 ** in the VDBE that record the limit and offset counters.
   9491 **
   9492 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   9493 ** These addresses must be stored so that we can go back and fill in
   9494 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   9495 ** the number of columns in P2 can be computed at the same time
   9496 ** as the OP_OpenEphm instruction is coded because not
   9497 ** enough information about the compound query is known at that point.
   9498 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   9499 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
   9500 ** sequences for the ORDER BY clause.
   9501 */
   9502 struct Select {
   9503   ExprList *pEList;      /* The fields of the result */
   9504   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   9505   char affinity;         /* MakeRecord with this affinity for SRT_Set */
   9506   u16 selFlags;          /* Various SF_* values */
   9507   SrcList *pSrc;         /* The FROM clause */
   9508   Expr *pWhere;          /* The WHERE clause */
   9509   ExprList *pGroupBy;    /* The GROUP BY clause */
   9510   Expr *pHaving;         /* The HAVING clause */
   9511   ExprList *pOrderBy;    /* The ORDER BY clause */
   9512   Select *pPrior;        /* Prior select in a compound select statement */
   9513   Select *pNext;         /* Next select to the left in a compound */
   9514   Select *pRightmost;    /* Right-most select in a compound select statement */
   9515   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   9516   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
   9517   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   9518   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
   9519 };
   9520 
   9521 /*
   9522 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   9523 ** "Select Flag".
   9524 */
   9525 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
   9526 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
   9527 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
   9528 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
   9529 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
   9530 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
   9531 
   9532 
   9533 /*
   9534 ** The results of a select can be distributed in several ways.  The
   9535 ** "SRT" prefix means "SELECT Result Type".
   9536 */
   9537 #define SRT_Union        1  /* Store result as keys in an index */
   9538 #define SRT_Except       2  /* Remove result from a UNION index */
   9539 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   9540 #define SRT_Discard      4  /* Do not save the results anywhere */
   9541 
   9542 /* The ORDER BY clause is ignored for all of the above */
   9543 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
   9544 
   9545 #define SRT_Output       5  /* Output each row of result */
   9546 #define SRT_Mem          6  /* Store result in a memory cell */
   9547 #define SRT_Set          7  /* Store results as keys in an index */
   9548 #define SRT_Table        8  /* Store result as data with an automatic rowid */
   9549 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
   9550 #define SRT_Coroutine   10  /* Generate a single row of result */
   9551 
   9552 /*
   9553 ** A structure used to customize the behavior of sqlite3Select(). See
   9554 ** comments above sqlite3Select() for details.
   9555 */
   9556 typedef struct SelectDest SelectDest;
   9557 struct SelectDest {
   9558   u8 eDest;         /* How to dispose of the results */
   9559   u8 affinity;      /* Affinity used when eDest==SRT_Set */
   9560   int iParm;        /* A parameter used by the eDest disposal method */
   9561   int iMem;         /* Base register where results are written */
   9562   int nMem;         /* Number of registers allocated */
   9563 };
   9564 
   9565 /*
   9566 ** During code generation of statements that do inserts into AUTOINCREMENT
   9567 ** tables, the following information is attached to the Table.u.autoInc.p
   9568 ** pointer of each autoincrement table to record some side information that
   9569 ** the code generator needs.  We have to keep per-table autoincrement
   9570 ** information in case inserts are down within triggers.  Triggers do not
   9571 ** normally coordinate their activities, but we do need to coordinate the
   9572 ** loading and saving of autoincrement information.
   9573 */
   9574 struct AutoincInfo {
   9575   AutoincInfo *pNext;   /* Next info block in a list of them all */
   9576   Table *pTab;          /* Table this info block refers to */
   9577   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   9578   int regCtr;           /* Memory register holding the rowid counter */
   9579 };
   9580 
   9581 /*
   9582 ** Size of the column cache
   9583 */
   9584 #ifndef SQLITE_N_COLCACHE
   9585 # define SQLITE_N_COLCACHE 10
   9586 #endif
   9587 
   9588 /*
   9589 ** At least one instance of the following structure is created for each
   9590 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   9591 ** statement. All such objects are stored in the linked list headed at
   9592 ** Parse.pTriggerPrg and deleted once statement compilation has been
   9593 ** completed.
   9594 **
   9595 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   9596 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   9597 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   9598 ** The Parse.pTriggerPrg list never contains two entries with the same
   9599 ** values for both pTrigger and orconf.
   9600 **
   9601 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   9602 ** accessed (or set to 0 for triggers fired as a result of INSERT
   9603 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   9604 ** a mask of new.* columns used by the program.
   9605 */
   9606 struct TriggerPrg {
   9607   Trigger *pTrigger;      /* Trigger this program was coded from */
   9608   int orconf;             /* Default ON CONFLICT policy */
   9609   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   9610   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   9611   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   9612 };
   9613 
   9614 /*
   9615 ** An SQL parser context.  A copy of this structure is passed through
   9616 ** the parser and down into all the parser action routine in order to
   9617 ** carry around information that is global to the entire parse.
   9618 **
   9619 ** The structure is divided into two parts.  When the parser and code
   9620 ** generate call themselves recursively, the first part of the structure
   9621 ** is constant but the second part is reset at the beginning and end of
   9622 ** each recursion.
   9623 **
   9624 ** The nTableLock and aTableLock variables are only used if the shared-cache
   9625 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   9626 ** used to store the set of table-locks required by the statement being
   9627 ** compiled. Function sqlite3TableLock() is used to add entries to the
   9628 ** list.
   9629 */
   9630 struct Parse {
   9631   sqlite3 *db;         /* The main database structure */
   9632   int rc;              /* Return code from execution */
   9633   char *zErrMsg;       /* An error message */
   9634   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   9635   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   9636   u8 nameClash;        /* A permanent table name clashes with temp table name */
   9637   u8 checkSchema;      /* Causes schema cookie check after an error */
   9638   u8 nested;           /* Number of nested calls to the parser/code generator */
   9639   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
   9640   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   9641   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
   9642   int aTempReg[8];     /* Holding area for temporary registers */
   9643   int nRangeReg;       /* Size of the temporary register block */
   9644   int iRangeReg;       /* First register in temporary register block */
   9645   int nErr;            /* Number of errors seen */
   9646   int nTab;            /* Number of previously allocated VDBE cursors */
   9647   int nMem;            /* Number of memory cells used so far */
   9648   int nSet;            /* Number of sets used so far */
   9649   int ckBase;          /* Base register of data during check constraints */
   9650   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   9651   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   9652   u8 nColCache;        /* Number of entries in the column cache */
   9653   u8 iColCache;        /* Next entry of the cache to replace */
   9654   struct yColCache {
   9655     int iTable;           /* Table cursor number */
   9656     int iColumn;          /* Table column number */
   9657     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   9658     int iLevel;           /* Nesting level */
   9659     int iReg;             /* Reg with value of this column. 0 means none. */
   9660     int lru;              /* Least recently used entry has the smallest value */
   9661   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   9662   u32 writeMask;       /* Start a write transaction on these databases */
   9663   u32 cookieMask;      /* Bitmask of schema verified databases */
   9664   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
   9665   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   9666   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
   9667   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
   9668 #ifndef SQLITE_OMIT_SHARED_CACHE
   9669   int nTableLock;        /* Number of locks in aTableLock */
   9670   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   9671 #endif
   9672   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   9673   int regRoot;         /* Register holding root page number for new objects */
   9674   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   9675   int nMaxArg;         /* Max args passed to user function by sub-program */
   9676 
   9677   /* Information used while coding trigger programs. */
   9678   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   9679   Table *pTriggerTab;  /* Table triggers are being coded for */
   9680   u32 oldmask;         /* Mask of old.* columns referenced */
   9681   u32 newmask;         /* Mask of new.* columns referenced */
   9682   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   9683   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   9684   u8 disableTriggers;  /* True to disable triggers */
   9685 
   9686   /* Above is constant between recursions.  Below is reset before and after
   9687   ** each recursion */
   9688 
   9689   int nVar;            /* Number of '?' variables seen in the SQL so far */
   9690   int nVarExpr;        /* Number of used slots in apVarExpr[] */
   9691   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
   9692   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
   9693   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
   9694   int nAlias;          /* Number of aliased result set columns */
   9695   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
   9696   int *aAlias;         /* Register used to hold aliased result */
   9697   u8 explain;          /* True if the EXPLAIN flag is found on the query */
   9698   Token sNameToken;    /* Token with unqualified schema object name */
   9699   Token sLastToken;    /* The last token parsed */
   9700   const char *zTail;   /* All SQL text past the last semicolon parsed */
   9701   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
   9702   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   9703   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   9704 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9705   Token sArg;                /* Complete text of a module argument */
   9706   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
   9707   int nVtabLock;             /* Number of virtual tables to lock */
   9708   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
   9709 #endif
   9710   int nHeight;            /* Expression tree height of current sub-select */
   9711   Table *pZombieTab;      /* List of Table objects to delete after code gen */
   9712   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
   9713 };
   9714 
   9715 #ifdef SQLITE_OMIT_VIRTUALTABLE
   9716   #define IN_DECLARE_VTAB 0
   9717 #else
   9718   #define IN_DECLARE_VTAB (pParse->declareVtab)
   9719 #endif
   9720 
   9721 /*
   9722 ** An instance of the following structure can be declared on a stack and used
   9723 ** to save the Parse.zAuthContext value so that it can be restored later.
   9724 */
   9725 struct AuthContext {
   9726   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   9727   Parse *pParse;              /* The Parse structure */
   9728 };
   9729 
   9730 /*
   9731 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
   9732 */
   9733 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
   9734 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
   9735 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   9736 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   9737 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   9738 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
   9739 
   9740 /*
   9741  * Each trigger present in the database schema is stored as an instance of
   9742  * struct Trigger.
   9743  *
   9744  * Pointers to instances of struct Trigger are stored in two ways.
   9745  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   9746  *    database). This allows Trigger structures to be retrieved by name.
   9747  * 2. All triggers associated with a single table form a linked list, using the
   9748  *    pNext member of struct Trigger. A pointer to the first element of the
   9749  *    linked list is stored as the "pTrigger" member of the associated
   9750  *    struct Table.
   9751  *
   9752  * The "step_list" member points to the first element of a linked list
   9753  * containing the SQL statements specified as the trigger program.
   9754  */
   9755 struct Trigger {
   9756   char *zName;            /* The name of the trigger                        */
   9757   char *table;            /* The table or view to which the trigger applies */
   9758   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   9759   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   9760   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   9761   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   9762                              the <column-list> is stored here */
   9763   Schema *pSchema;        /* Schema containing the trigger */
   9764   Schema *pTabSchema;     /* Schema containing the table */
   9765   TriggerStep *step_list; /* Link list of trigger program steps             */
   9766   Trigger *pNext;         /* Next trigger associated with the table */
   9767 };
   9768 
   9769 /*
   9770 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   9771 ** determine which.
   9772 **
   9773 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   9774 ** In that cases, the constants below can be ORed together.
   9775 */
   9776 #define TRIGGER_BEFORE  1
   9777 #define TRIGGER_AFTER   2
   9778 
   9779 /*
   9780  * An instance of struct TriggerStep is used to store a single SQL statement
   9781  * that is a part of a trigger-program.
   9782  *
   9783  * Instances of struct TriggerStep are stored in a singly linked list (linked
   9784  * using the "pNext" member) referenced by the "step_list" member of the
   9785  * associated struct Trigger instance. The first element of the linked list is
   9786  * the first step of the trigger-program.
   9787  *
   9788  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   9789  * "SELECT" statement. The meanings of the other members is determined by the
   9790  * value of "op" as follows:
   9791  *
   9792  * (op == TK_INSERT)
   9793  * orconf    -> stores the ON CONFLICT algorithm
   9794  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   9795  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   9796  * target    -> A token holding the quoted name of the table to insert into.
   9797  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   9798  *              this stores values to be inserted. Otherwise NULL.
   9799  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   9800  *              statement, then this stores the column-names to be
   9801  *              inserted into.
   9802  *
   9803  * (op == TK_DELETE)
   9804  * target    -> A token holding the quoted name of the table to delete from.
   9805  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   9806  *              Otherwise NULL.
   9807  *
   9808  * (op == TK_UPDATE)
   9809  * target    -> A token holding the quoted name of the table to update rows of.
   9810  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   9811  *              Otherwise NULL.
   9812  * pExprList -> A list of the columns to update and the expressions to update
   9813  *              them to. See sqlite3Update() documentation of "pChanges"
   9814  *              argument.
   9815  *
   9816  */
   9817 struct TriggerStep {
   9818   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   9819   u8 orconf;           /* OE_Rollback etc. */
   9820   Trigger *pTrig;      /* The trigger that this step is a part of */
   9821   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
   9822   Token target;        /* Target table for DELETE, UPDATE, INSERT */
   9823   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   9824   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
   9825   IdList *pIdList;     /* Column names for INSERT */
   9826   TriggerStep *pNext;  /* Next in the link-list */
   9827   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   9828 };
   9829 
   9830 /*
   9831 ** The following structure contains information used by the sqliteFix...
   9832 ** routines as they walk the parse tree to make database references
   9833 ** explicit.
   9834 */
   9835 typedef struct DbFixer DbFixer;
   9836 struct DbFixer {
   9837   Parse *pParse;      /* The parsing context.  Error messages written here */
   9838   const char *zDb;    /* Make sure all objects are contained in this database */
   9839   const char *zType;  /* Type of the container - used for error messages */
   9840   const Token *pName; /* Name of the container - used for error messages */
   9841 };
   9842 
   9843 /*
   9844 ** An objected used to accumulate the text of a string where we
   9845 ** do not necessarily know how big the string will be in the end.
   9846 */
   9847 struct StrAccum {
   9848   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   9849   char *zBase;         /* A base allocation.  Not from malloc. */
   9850   char *zText;         /* The string collected so far */
   9851   int  nChar;          /* Length of the string so far */
   9852   int  nAlloc;         /* Amount of space allocated in zText */
   9853   int  mxAlloc;        /* Maximum allowed string length */
   9854   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
   9855   u8   useMalloc;      /* True if zText is enlargeable using realloc */
   9856   u8   tooBig;         /* Becomes true if string size exceeds limits */
   9857 };
   9858 
   9859 /*
   9860 ** A pointer to this structure is used to communicate information
   9861 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   9862 */
   9863 typedef struct {
   9864   sqlite3 *db;        /* The database being initialized */
   9865   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   9866   char **pzErrMsg;    /* Error message stored here */
   9867   int rc;             /* Result code stored here */
   9868 } InitData;
   9869 
   9870 /*
   9871 ** Structure containing global configuration data for the SQLite library.
   9872 **
   9873 ** This structure also contains some state information.
   9874 */
   9875 struct Sqlite3Config {
   9876   int bMemstat;                     /* True to enable memory status */
   9877   int bCoreMutex;                   /* True to enable core mutexing */
   9878   int bFullMutex;                   /* True to enable full mutexing */
   9879   int mxStrlen;                     /* Maximum string length */
   9880   int szLookaside;                  /* Default lookaside buffer size */
   9881   int nLookaside;                   /* Default lookaside buffer count */
   9882   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   9883   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   9884   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
   9885   void *pHeap;                      /* Heap storage space */
   9886   int nHeap;                        /* Size of pHeap[] */
   9887   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   9888   void *pScratch;                   /* Scratch memory */
   9889   int szScratch;                    /* Size of each scratch buffer */
   9890   int nScratch;                     /* Number of scratch buffers */
   9891   void *pPage;                      /* Page cache memory */
   9892   int szPage;                       /* Size of each page in pPage[] */
   9893   int nPage;                        /* Number of pages in pPage[] */
   9894   int mxParserStack;                /* maximum depth of the parser stack */
   9895   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   9896   /* The above might be initialized to non-zero.  The following need to always
   9897   ** initially be zero, however. */
   9898   int isInit;                       /* True after initialization has finished */
   9899   int inProgress;                   /* True while initialization in progress */
   9900   int isMutexInit;                  /* True after mutexes are initialized */
   9901   int isMallocInit;                 /* True after malloc is initialized */
   9902   int isPCacheInit;                 /* True after malloc is initialized */
   9903   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   9904   int nRefInitMutex;                /* Number of users of pInitMutex */
   9905   void (*xLog)(void*,int,const char*); /* Function for logging */
   9906   void *pLogArg;                       /* First argument to xLog() */
   9907 };
   9908 
   9909 /*
   9910 ** Context pointer passed down through the tree-walk.
   9911 */
   9912 struct Walker {
   9913   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   9914   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   9915   Parse *pParse;                            /* Parser context.  */
   9916   union {                                   /* Extra data for callback */
   9917     NameContext *pNC;                          /* Naming context */
   9918     int i;                                     /* Integer value */
   9919   } u;
   9920 };
   9921 
   9922 /* Forward declarations */
   9923 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   9924 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   9925 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   9926 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   9927 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   9928 
   9929 /*
   9930 ** Return code from the parse-tree walking primitives and their
   9931 ** callbacks.
   9932 */
   9933 #define WRC_Continue    0   /* Continue down into children */
   9934 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   9935 #define WRC_Abort       2   /* Abandon the tree walk */
   9936 
   9937 /*
   9938 ** Assuming zIn points to the first byte of a UTF-8 character,
   9939 ** advance zIn to point to the first byte of the next UTF-8 character.
   9940 */
   9941 #define SQLITE_SKIP_UTF8(zIn) {                        \
   9942   if( (*(zIn++))>=0xc0 ){                              \
   9943     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   9944   }                                                    \
   9945 }
   9946 
   9947 /*
   9948 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   9949 ** the same name but without the _BKPT suffix.  These macros invoke
   9950 ** routines that report the line-number on which the error originated
   9951 ** using sqlite3_log().  The routines also provide a convenient place
   9952 ** to set a debugger breakpoint.
   9953 */
   9954 SQLITE_PRIVATE int sqlite3CorruptError(int);
   9955 SQLITE_PRIVATE int sqlite3MisuseError(int);
   9956 SQLITE_PRIVATE int sqlite3CantopenError(int);
   9957 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   9958 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   9959 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   9960 
   9961 
   9962 /*
   9963 ** The ctype.h header is needed for non-ASCII systems.  It is also
   9964 ** needed by FTS3 when FTS3 is included in the amalgamation.
   9965 */
   9966 #if !defined(SQLITE_ASCII) || \
   9967     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   9968 # include <ctype.h>
   9969 #endif
   9970 
   9971 /*
   9972 ** The following macros mimic the standard library functions toupper(),
   9973 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   9974 ** sqlite versions only work for ASCII characters, regardless of locale.
   9975 */
   9976 #ifdef SQLITE_ASCII
   9977 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   9978 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   9979 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   9980 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   9981 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   9982 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   9983 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   9984 #else
   9985 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   9986 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   9987 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   9988 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   9989 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   9990 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   9991 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   9992 #endif
   9993 
   9994 /*
   9995 ** Internal function prototypes
   9996 */
   9997 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
   9998 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
   9999 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   10000 #define sqlite3StrNICmp sqlite3_strnicmp
   10001 
   10002 SQLITE_PRIVATE int sqlite3MallocInit(void);
   10003 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   10004 SQLITE_PRIVATE void *sqlite3Malloc(int);
   10005 SQLITE_PRIVATE void *sqlite3MallocZero(int);
   10006 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
   10007 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
   10008 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   10009 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
   10010 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
   10011 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
   10012 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
   10013 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   10014 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   10015 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   10016 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
   10017 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
   10018 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   10019 SQLITE_PRIVATE void sqlite3PageFree(void*);
   10020 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   10021 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   10022 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
   10023 
   10024 /*
   10025 ** On systems with ample stack space and that support alloca(), make
   10026 ** use of alloca() to obtain space for large automatic objects.  By default,
   10027 ** obtain space from malloc().
   10028 **
   10029 ** The alloca() routine never returns NULL.  This will cause code paths
   10030 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   10031 */
   10032 #ifdef SQLITE_USE_ALLOCA
   10033 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   10034 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   10035 # define sqlite3StackFree(D,P)
   10036 #else
   10037 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   10038 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   10039 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   10040 #endif
   10041 
   10042 #ifdef SQLITE_ENABLE_MEMSYS3
   10043 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   10044 #endif
   10045 #ifdef SQLITE_ENABLE_MEMSYS5
   10046 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   10047 #endif
   10048 
   10049 
   10050 #ifndef SQLITE_MUTEX_OMIT
   10051 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
   10052 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   10053 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   10054 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   10055 #endif
   10056 
   10057 SQLITE_PRIVATE int sqlite3StatusValue(int);
   10058 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
   10059 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
   10060 
   10061 SQLITE_PRIVATE int sqlite3IsNaN(double);
   10062 
   10063 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
   10064 #ifndef SQLITE_OMIT_TRACE
   10065 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
   10066 #endif
   10067 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   10068 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   10069 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
   10070 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   10071 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   10072 #endif
   10073 #if defined(SQLITE_TEST)
   10074 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   10075 #endif
   10076 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
   10077 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   10078 SQLITE_PRIVATE int sqlite3Dequote(char*);
   10079 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   10080 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   10081 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   10082 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   10083 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   10084 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   10085 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   10086 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   10087 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   10088 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   10089 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
   10090 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   10091 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   10092 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
   10093 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   10094 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   10095 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   10096 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
   10097 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   10098 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   10099 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   10100 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   10101 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
   10102 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
   10103 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   10104 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   10105 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   10106 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   10107 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
   10108 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   10109 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   10110 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   10111 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
   10112 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
   10113 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   10114 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
   10115 
   10116 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   10117 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   10118 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   10119 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   10120 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   10121 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   10122 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   10123 
   10124 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   10125 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   10126 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   10127 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
   10128 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   10129 
   10130 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
   10131 
   10132 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   10133 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   10134 #else
   10135 # define sqlite3ViewGetColumnNames(A,B) 0
   10136 #endif
   10137 
   10138 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   10139 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
   10140 #ifndef SQLITE_OMIT_AUTOINCREMENT
   10141 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   10142 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   10143 #else
   10144 # define sqlite3AutoincrementBegin(X)
   10145 # define sqlite3AutoincrementEnd(X)
   10146 #endif
   10147 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
   10148 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
   10149 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   10150 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   10151 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   10152 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   10153 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   10154                                       Token*, Select*, Expr*, IdList*);
   10155 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   10156 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   10157 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   10158 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   10159 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   10160 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   10161 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   10162                         Token*, int, int);
   10163 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   10164 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   10165 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   10166                          Expr*,ExprList*,int,Expr*,Expr*);
   10167 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   10168 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   10169 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   10170 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   10171 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   10172 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
   10173 #endif
   10174 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
   10175 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
   10176 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
   10177 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   10178 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
   10179 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   10180 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
   10181 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   10182 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   10183 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
   10184 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   10185 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   10186 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   10187 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
   10188 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
   10189 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   10190 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   10191 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   10192 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
   10193 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
   10194 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   10195 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   10196 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   10197 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
   10198 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   10199 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   10200 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   10201 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
   10202 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
   10203 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   10204 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
   10205 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   10206 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   10207 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   10208 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   10209 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   10210 SQLITE_PRIVATE void sqlite3PrngResetState(void);
   10211 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
   10212 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   10213 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   10214 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
   10215 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
   10216 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   10217 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   10218 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   10219 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   10220 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
   10221 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   10222 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   10223 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
   10224 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   10225 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   10226 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
   10227 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
   10228 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
   10229 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
   10230                                      int*,int,int,int,int,int*);
   10231 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
   10232 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
   10233 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   10234 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   10235 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   10236 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
   10237 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   10238 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   10239 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   10240 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   10241 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   10242 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
   10243 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
   10244 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
   10245 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   10246 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
   10247 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   10248 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   10249 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   10250 
   10251 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   10252 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
   10253 #endif
   10254 
   10255 #ifndef SQLITE_OMIT_TRIGGER
   10256 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   10257                            Expr*,int, int);
   10258 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   10259 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   10260 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   10261 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   10262 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   10263 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   10264                             int, int, int);
   10265 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   10266   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   10267 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   10268 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
   10269 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   10270                                         ExprList*,Select*,u8);
   10271 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
   10272 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
   10273 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   10274 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   10275 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   10276 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   10277 #else
   10278 # define sqlite3TriggersExist(B,C,D,E,F) 0
   10279 # define sqlite3DeleteTrigger(A,B)
   10280 # define sqlite3DropTriggerPtr(A,B)
   10281 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   10282 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   10283 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   10284 # define sqlite3TriggerList(X, Y) 0
   10285 # define sqlite3ParseToplevel(p) p
   10286 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   10287 #endif
   10288 
   10289 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   10290 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   10291 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   10292 #ifndef SQLITE_OMIT_AUTHORIZATION
   10293 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   10294 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   10295 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   10296 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   10297 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   10298 #else
   10299 # define sqlite3AuthRead(a,b,c,d)
   10300 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   10301 # define sqlite3AuthContextPush(a,b,c)
   10302 # define sqlite3AuthContextPop(a)  ((void)(a))
   10303 #endif
   10304 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   10305 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   10306 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
   10307                        int omitJournal, int nCache, int flags, Btree **ppBtree);
   10308 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   10309 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   10310 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   10311 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   10312 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   10313 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   10314 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
   10315 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   10316 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
   10317 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   10318 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   10319 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
   10320 
   10321 /*
   10322 ** Routines to read and write variable-length integers.  These used to
   10323 ** be defined locally, but now we use the varint routines in the util.c
   10324 ** file.  Code should use the MACRO forms below, as the Varint32 versions
   10325 ** are coded to assume the single byte case is already handled (which
   10326 ** the MACRO form does).
   10327 */
   10328 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   10329 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
   10330 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   10331 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   10332 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   10333 
   10334 /*
   10335 ** The header of a record consists of a sequence variable-length integers.
   10336 ** These integers are almost always small and are encoded as a single byte.
   10337 ** The following macros take advantage this fact to provide a fast encode
   10338 ** and decode of the integers in a record header.  It is faster for the common
   10339 ** case where the integer is a single byte.  It is a little slower when the
   10340 ** integer is two or more bytes.  But overall it is faster.
   10341 **
   10342 ** The following expressions are equivalent:
   10343 **
   10344 **     x = sqlite3GetVarint32( A, &B );
   10345 **     x = sqlite3PutVarint32( A, B );
   10346 **
   10347 **     x = getVarint32( A, B );
   10348 **     x = putVarint32( A, B );
   10349 **
   10350 */
   10351 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
   10352 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
   10353 #define getVarint    sqlite3GetVarint
   10354 #define putVarint    sqlite3PutVarint
   10355 
   10356 
   10357 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
   10358 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
   10359 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   10360 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   10361 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   10362 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
   10363 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
   10364 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   10365 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   10366 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   10367 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   10368 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   10369 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   10370 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   10371 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
   10372 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   10373 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   10374 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   10375 
   10376 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   10377 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   10378 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   10379                         void(*)(void*));
   10380 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   10381 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   10382 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
   10383 #ifdef SQLITE_ENABLE_STAT2
   10384 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
   10385 #endif
   10386 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   10387 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   10388 #ifndef SQLITE_AMALGAMATION
   10389 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   10390 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   10391 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   10392 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   10393 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   10394 SQLITE_PRIVATE int sqlite3PendingByte;
   10395 #endif
   10396 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
   10397 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   10398 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
   10399 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   10400 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   10401 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   10402 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   10403 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
   10404 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   10405 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   10406 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   10407 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   10408 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   10409 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   10410 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   10411 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
   10412 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
   10413 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   10414 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   10415 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   10416 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   10417 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   10418 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
   10419 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   10420 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   10421 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   10422 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
   10423 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
   10424 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   10425 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   10426 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
   10427 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   10428   void (*)(sqlite3_context*,int,sqlite3_value **),
   10429   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
   10430 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   10431 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   10432 
   10433 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
   10434 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   10435 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   10436 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   10437 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   10438 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   10439 
   10440 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   10441 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   10442 
   10443 /*
   10444 ** The interface to the LEMON-generated parser
   10445 */
   10446 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
   10447 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
   10448 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   10449 #ifdef YYTRACKMAXSTACKDEPTH
   10450 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   10451 #endif
   10452 
   10453 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   10454 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   10455 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   10456 #else
   10457 # define sqlite3CloseExtensions(X)
   10458 #endif
   10459 
   10460 #ifndef SQLITE_OMIT_SHARED_CACHE
   10461 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   10462 #else
   10463   #define sqlite3TableLock(v,w,x,y,z)
   10464 #endif
   10465 
   10466 #ifdef SQLITE_TEST
   10467 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   10468 #endif
   10469 
   10470 #ifdef SQLITE_OMIT_VIRTUALTABLE
   10471 #  define sqlite3VtabClear(Y)
   10472 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   10473 #  define sqlite3VtabRollback(X)
   10474 #  define sqlite3VtabCommit(X)
   10475 #  define sqlite3VtabInSync(db) 0
   10476 #  define sqlite3VtabLock(X)
   10477 #  define sqlite3VtabUnlock(X)
   10478 #  define sqlite3VtabUnlockList(X)
   10479 #else
   10480 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
   10481 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
   10482 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   10483 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   10484 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   10485 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   10486 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   10487 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   10488 #endif
   10489 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   10490 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
   10491 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   10492 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   10493 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   10494 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   10495 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   10496 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   10497 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   10498 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   10499 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   10500 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   10501 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   10502 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   10503 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   10504 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   10505 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   10506 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
   10507 
   10508 /* Declarations for functions in fkey.c. All of these are replaced by
   10509 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   10510 ** key functionality is available. If OMIT_TRIGGER is defined but
   10511 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   10512 ** this case foreign keys are parsed, but no other functionality is
   10513 ** provided (enforcement of FK constraints requires the triggers sub-system).
   10514 */
   10515 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   10516 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
   10517 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   10518 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
   10519 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   10520 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   10521 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   10522 #else
   10523   #define sqlite3FkActions(a,b,c,d)
   10524   #define sqlite3FkCheck(a,b,c,d)
   10525   #define sqlite3FkDropTable(a,b,c)
   10526   #define sqlite3FkOldmask(a,b)      0
   10527   #define sqlite3FkRequired(a,b,c,d) 0
   10528 #endif
   10529 #ifndef SQLITE_OMIT_FOREIGN_KEY
   10530 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
   10531 #else
   10532   #define sqlite3FkDelete(a)
   10533 #endif
   10534 
   10535 
   10536 /*
   10537 ** Available fault injectors.  Should be numbered beginning with 0.
   10538 */
   10539 #define SQLITE_FAULTINJECTOR_MALLOC     0
   10540 #define SQLITE_FAULTINJECTOR_COUNT      1
   10541 
   10542 /*
   10543 ** The interface to the code in fault.c used for identifying "benign"
   10544 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
   10545 ** is not defined.
   10546 */
   10547 #ifndef SQLITE_OMIT_BUILTIN_TEST
   10548 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   10549 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   10550 #else
   10551   #define sqlite3BeginBenignMalloc()
   10552   #define sqlite3EndBenignMalloc()
   10553 #endif
   10554 
   10555 #define IN_INDEX_ROWID           1
   10556 #define IN_INDEX_EPH             2
   10557 #define IN_INDEX_INDEX           3
   10558 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
   10559 
   10560 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   10561 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   10562 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
   10563 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   10564 #else
   10565   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
   10566 #endif
   10567 
   10568 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   10569 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
   10570 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
   10571 
   10572 #if SQLITE_MAX_EXPR_DEPTH>0
   10573 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
   10574 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   10575 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   10576 #else
   10577   #define sqlite3ExprSetHeight(x,y)
   10578   #define sqlite3SelectExprHeight(x) 0
   10579   #define sqlite3ExprCheckHeight(x,y)
   10580 #endif
   10581 
   10582 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   10583 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   10584 
   10585 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   10586 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   10587 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   10588 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   10589 #else
   10590   #define sqlite3ConnectionBlocked(x,y)
   10591   #define sqlite3ConnectionUnlocked(x)
   10592   #define sqlite3ConnectionClosed(x)
   10593 #endif
   10594 
   10595 #ifdef SQLITE_DEBUG
   10596 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   10597 #endif
   10598 
   10599 /*
   10600 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   10601 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   10602 ** print I/O tracing messages.
   10603 */
   10604 #ifdef SQLITE_ENABLE_IOTRACE
   10605 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   10606 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   10607 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
   10608 #else
   10609 # define IOTRACE(A)
   10610 # define sqlite3VdbeIOTraceSql(X)
   10611 #endif
   10612 
   10613 #endif
   10614 
   10615 /************** End of sqliteInt.h *******************************************/
   10616 /************** Begin file global.c ******************************************/
   10617 /*
   10618 ** 2008 June 13
   10619 **
   10620 ** The author disclaims copyright to this source code.  In place of
   10621 ** a legal notice, here is a blessing:
   10622 **
   10623 **    May you do good and not evil.
   10624 **    May you find forgiveness for yourself and forgive others.
   10625 **    May you share freely, never taking more than you give.
   10626 **
   10627 *************************************************************************
   10628 **
   10629 ** This file contains definitions of global variables and contants.
   10630 */
   10631 
   10632 /* An array to map all upper-case characters into their corresponding
   10633 ** lower-case character.
   10634 **
   10635 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   10636 ** handle case conversions for the UTF character set since the tables
   10637 ** involved are nearly as big or bigger than SQLite itself.
   10638 */
   10639 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   10640 #ifdef SQLITE_ASCII
   10641       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   10642      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   10643      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   10644      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   10645     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   10646     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   10647     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   10648     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   10649     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   10650     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   10651     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   10652     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   10653     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   10654     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   10655     252,253,254,255
   10656 #endif
   10657 #ifdef SQLITE_EBCDIC
   10658       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   10659      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   10660      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   10661      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   10662      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   10663      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   10664      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
   10665     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
   10666     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   10667     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
   10668     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   10669     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   10670     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   10671     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   10672     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
   10673     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
   10674 #endif
   10675 };
   10676 
   10677 /*
   10678 ** The following 256 byte lookup table is used to support SQLites built-in
   10679 ** equivalents to the following standard library functions:
   10680 **
   10681 **   isspace()                        0x01
   10682 **   isalpha()                        0x02
   10683 **   isdigit()                        0x04
   10684 **   isalnum()                        0x06
   10685 **   isxdigit()                       0x08
   10686 **   toupper()                        0x20
   10687 **   SQLite identifier character      0x40
   10688 **
   10689 ** Bit 0x20 is set if the mapped character requires translation to upper
   10690 ** case. i.e. if the character is a lower-case ASCII character.
   10691 ** If x is a lower-case ASCII character, then its upper-case equivalent
   10692 ** is (x - 0x20). Therefore toupper() can be implemented as:
   10693 **
   10694 **   (x & ~(map[x]&0x20))
   10695 **
   10696 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
   10697 ** array. tolower() is used more often than toupper() by SQLite.
   10698 **
   10699 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
   10700 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   10701 ** non-ASCII UTF character. Hence the test for whether or not a character is
   10702 ** part of an identifier is 0x46.
   10703 **
   10704 ** SQLite's versions are identical to the standard versions assuming a
   10705 ** locale of "C". They are implemented as macros in sqliteInt.h.
   10706 */
   10707 #ifdef SQLITE_ASCII
   10708 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   10709   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   10710   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   10711   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   10712   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   10713   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
   10714   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   10715   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   10716   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   10717 
   10718   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   10719   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   10720   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   10721   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   10722   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   10723   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   10724   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   10725   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   10726 
   10727   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   10728   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   10729   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   10730   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   10731   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   10732   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   10733   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   10734   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   10735 
   10736   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   10737   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   10738   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   10739   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   10740   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   10741   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   10742   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   10743   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   10744 };
   10745 #endif
   10746 
   10747 
   10748 
   10749 /*
   10750 ** The following singleton contains the global configuration for
   10751 ** the SQLite library.
   10752 */
   10753 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   10754    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   10755    1,                         /* bCoreMutex */
   10756    SQLITE_THREADSAFE==1,      /* bFullMutex */
   10757    0x7ffffffe,                /* mxStrlen */
   10758    100,                       /* szLookaside */
   10759    500,                       /* nLookaside */
   10760    {0,0,0,0,0,0,0,0},         /* m */
   10761    {0,0,0,0,0,0,0,0,0},       /* mutex */
   10762    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
   10763    (void*)0,                  /* pHeap */
   10764    0,                         /* nHeap */
   10765    0, 0,                      /* mnHeap, mxHeap */
   10766    (void*)0,                  /* pScratch */
   10767    0,                         /* szScratch */
   10768    0,                         /* nScratch */
   10769    (void*)0,                  /* pPage */
   10770    0,                         /* szPage */
   10771    0,                         /* nPage */
   10772    0,                         /* mxParserStack */
   10773    0,                         /* sharedCacheEnabled */
   10774    /* All the rest should always be initialized to zero */
   10775    0,                         /* isInit */
   10776    0,                         /* inProgress */
   10777    0,                         /* isMutexInit */
   10778    0,                         /* isMallocInit */
   10779    0,                         /* isPCacheInit */
   10780    0,                         /* pInitMutex */
   10781    0,                         /* nRefInitMutex */
   10782    0,                         /* xLog */
   10783    0,                         /* pLogArg */
   10784 };
   10785 
   10786 
   10787 /*
   10788 ** Hash table for global functions - functions common to all
   10789 ** database connections.  After initialization, this table is
   10790 ** read-only.
   10791 */
   10792 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   10793 
   10794 /*
   10795 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   10796 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   10797 ** the database page that contains the pending byte.  It never attempts
   10798 ** to read or write that page.  The pending byte page is set assign
   10799 ** for use by the VFS layers as space for managing file locks.
   10800 **
   10801 ** During testing, it is often desirable to move the pending byte to
   10802 ** a different position in the file.  This allows code that has to
   10803 ** deal with the pending byte to run on files that are much smaller
   10804 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   10805 ** move the pending byte.
   10806 **
   10807 ** IMPORTANT:  Changing the pending byte to any value other than
   10808 ** 0x40000000 results in an incompatible database file format!
   10809 ** Changing the pending byte during operating results in undefined
   10810 ** and dileterious behavior.
   10811 */
   10812 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   10813 
   10814 /*
   10815 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   10816 ** created by mkopcodeh.awk during compilation.  Data is obtained
   10817 ** from the comments following the "case OP_xxxx:" statements in
   10818 ** the vdbe.c file.
   10819 */
   10820 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   10821 
   10822 /************** End of global.c **********************************************/
   10823 /************** Begin file status.c ******************************************/
   10824 /*
   10825 ** 2008 June 18
   10826 **
   10827 ** The author disclaims copyright to this source code.  In place of
   10828 ** a legal notice, here is a blessing:
   10829 **
   10830 **    May you do good and not evil.
   10831 **    May you find forgiveness for yourself and forgive others.
   10832 **    May you share freely, never taking more than you give.
   10833 **
   10834 *************************************************************************
   10835 **
   10836 ** This module implements the sqlite3_status() interface and related
   10837 ** functionality.
   10838 */
   10839 
   10840 /*
   10841 ** Variables in which to record status information.
   10842 */
   10843 typedef struct sqlite3StatType sqlite3StatType;
   10844 static SQLITE_WSD struct sqlite3StatType {
   10845   int nowValue[9];         /* Current value */
   10846   int mxValue[9];          /* Maximum value */
   10847 } sqlite3Stat = { {0,}, {0,} };
   10848 
   10849 
   10850 /* The "wsdStat" macro will resolve to the status information
   10851 ** state vector.  If writable static data is unsupported on the target,
   10852 ** we have to locate the state vector at run-time.  In the more common
   10853 ** case where writable static data is supported, wsdStat can refer directly
   10854 ** to the "sqlite3Stat" state vector declared above.
   10855 */
   10856 #ifdef SQLITE_OMIT_WSD
   10857 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   10858 # define wsdStat x[0]
   10859 #else
   10860 # define wsdStatInit
   10861 # define wsdStat sqlite3Stat
   10862 #endif
   10863 
   10864 /*
   10865 ** Return the current value of a status parameter.
   10866 */
   10867 SQLITE_PRIVATE int sqlite3StatusValue(int op){
   10868   wsdStatInit;
   10869   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10870   return wsdStat.nowValue[op];
   10871 }
   10872 
   10873 /*
   10874 ** Add N to the value of a status record.  It is assumed that the
   10875 ** caller holds appropriate locks.
   10876 */
   10877 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
   10878   wsdStatInit;
   10879   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10880   wsdStat.nowValue[op] += N;
   10881   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   10882     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10883   }
   10884 }
   10885 
   10886 /*
   10887 ** Set the value of a status to X.
   10888 */
   10889 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
   10890   wsdStatInit;
   10891   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10892   wsdStat.nowValue[op] = X;
   10893   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   10894     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10895   }
   10896 }
   10897 
   10898 /*
   10899 ** Query status information.
   10900 **
   10901 ** This implementation assumes that reading or writing an aligned
   10902 ** 32-bit integer is an atomic operation.  If that assumption is not true,
   10903 ** then this routine is not threadsafe.
   10904 */
   10905 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   10906   wsdStatInit;
   10907   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   10908     return SQLITE_MISUSE_BKPT;
   10909   }
   10910   *pCurrent = wsdStat.nowValue[op];
   10911   *pHighwater = wsdStat.mxValue[op];
   10912   if( resetFlag ){
   10913     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10914   }
   10915   return SQLITE_OK;
   10916 }
   10917 
   10918 /*
   10919 ** Query status information for a single database connection
   10920 */
   10921 SQLITE_API int sqlite3_db_status(
   10922   sqlite3 *db,          /* The database connection whose status is desired */
   10923   int op,               /* Status verb */
   10924   int *pCurrent,        /* Write current value here */
   10925   int *pHighwater,      /* Write high-water mark here */
   10926   int resetFlag         /* Reset high-water mark if true */
   10927 ){
   10928   switch( op ){
   10929     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   10930       *pCurrent = db->lookaside.nOut;
   10931       *pHighwater = db->lookaside.mxOut;
   10932       if( resetFlag ){
   10933         db->lookaside.mxOut = db->lookaside.nOut;
   10934       }
   10935       break;
   10936     }
   10937     default: {
   10938       return SQLITE_ERROR;
   10939     }
   10940   }
   10941   return SQLITE_OK;
   10942 }
   10943 
   10944 /************** End of status.c **********************************************/
   10945 /************** Begin file date.c ********************************************/
   10946 /*
   10947 ** 2003 October 31
   10948 **
   10949 ** The author disclaims copyright to this source code.  In place of
   10950 ** a legal notice, here is a blessing:
   10951 **
   10952 **    May you do good and not evil.
   10953 **    May you find forgiveness for yourself and forgive others.
   10954 **    May you share freely, never taking more than you give.
   10955 **
   10956 *************************************************************************
   10957 ** This file contains the C functions that implement date and time
   10958 ** functions for SQLite.
   10959 **
   10960 ** There is only one exported symbol in this file - the function
   10961 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   10962 ** All other code has file scope.
   10963 **
   10964 ** SQLite processes all times and dates as Julian Day numbers.  The
   10965 ** dates and times are stored as the number of days since noon
   10966 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   10967 ** calendar system.
   10968 **
   10969 ** 1970-01-01 00:00:00 is JD 2440587.5
   10970 ** 2000-01-01 00:00:00 is JD 2451544.5
   10971 **
   10972 ** This implemention requires years to be expressed as a 4-digit number
   10973 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   10974 ** be represented, even though julian day numbers allow a much wider
   10975 ** range of dates.
   10976 **
   10977 ** The Gregorian calendar system is used for all dates and times,
   10978 ** even those that predate the Gregorian calendar.  Historians usually
   10979 ** use the Julian calendar for dates prior to 1582-10-15 and for some
   10980 ** dates afterwards, depending on locale.  Beware of this difference.
   10981 **
   10982 ** The conversion algorithms are implemented based on descriptions
   10983 ** in the following text:
   10984 **
   10985 **      Jean Meeus
   10986 **      Astronomical Algorithms, 2nd Edition, 1998
   10987 **      ISBM 0-943396-61-1
   10988 **      Willmann-Bell, Inc
   10989 **      Richmond, Virginia (USA)
   10990 */
   10991 #include <time.h>
   10992 
   10993 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   10994 
   10995 /*
   10996 ** On recent Windows platforms, the localtime_s() function is available
   10997 ** as part of the "Secure CRT". It is essentially equivalent to
   10998 ** localtime_r() available under most POSIX platforms, except that the
   10999 ** order of the parameters is reversed.
   11000 **
   11001 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   11002 **
   11003 ** If the user has not indicated to use localtime_r() or localtime_s()
   11004 ** already, check for an MSVC build environment that provides
   11005 ** localtime_s().
   11006 */
   11007 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
   11008      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   11009 #define HAVE_LOCALTIME_S 1
   11010 #endif
   11011 
   11012 /*
   11013 ** A structure for holding a single date and time.
   11014 */
   11015 typedef struct DateTime DateTime;
   11016 struct DateTime {
   11017   sqlite3_int64 iJD; /* The julian day number times 86400000 */
   11018   int Y, M, D;       /* Year, month, and day */
   11019   int h, m;          /* Hour and minutes */
   11020   int tz;            /* Timezone offset in minutes */
   11021   double s;          /* Seconds */
   11022   char validYMD;     /* True (1) if Y,M,D are valid */
   11023   char validHMS;     /* True (1) if h,m,s are valid */
   11024   char validJD;      /* True (1) if iJD is valid */
   11025   char validTZ;      /* True (1) if tz is valid */
   11026 };
   11027 
   11028 
   11029 /*
   11030 ** Convert zDate into one or more integers.  Additional arguments
   11031 ** come in groups of 5 as follows:
   11032 **
   11033 **       N       number of digits in the integer
   11034 **       min     minimum allowed value of the integer
   11035 **       max     maximum allowed value of the integer
   11036 **       nextC   first character after the integer
   11037 **       pVal    where to write the integers value.
   11038 **
   11039 ** Conversions continue until one with nextC==0 is encountered.
   11040 ** The function returns the number of successful conversions.
   11041 */
   11042 static int getDigits(const char *zDate, ...){
   11043   va_list ap;
   11044   int val;
   11045   int N;
   11046   int min;
   11047   int max;
   11048   int nextC;
   11049   int *pVal;
   11050   int cnt = 0;
   11051   va_start(ap, zDate);
   11052   do{
   11053     N = va_arg(ap, int);
   11054     min = va_arg(ap, int);
   11055     max = va_arg(ap, int);
   11056     nextC = va_arg(ap, int);
   11057     pVal = va_arg(ap, int*);
   11058     val = 0;
   11059     while( N-- ){
   11060       if( !sqlite3Isdigit(*zDate) ){
   11061         goto end_getDigits;
   11062       }
   11063       val = val*10 + *zDate - '0';
   11064       zDate++;
   11065     }
   11066     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
   11067       goto end_getDigits;
   11068     }
   11069     *pVal = val;
   11070     zDate++;
   11071     cnt++;
   11072   }while( nextC );
   11073 end_getDigits:
   11074   va_end(ap);
   11075   return cnt;
   11076 }
   11077 
   11078 /*
   11079 ** Read text from z[] and convert into a floating point number.  Return
   11080 ** the number of digits converted.
   11081 */
   11082 #define getValue sqlite3AtoF
   11083 
   11084 /*
   11085 ** Parse a timezone extension on the end of a date-time.
   11086 ** The extension is of the form:
   11087 **
   11088 **        (+/-)HH:MM
   11089 **
   11090 ** Or the "zulu" notation:
   11091 **
   11092 **        Z
   11093 **
   11094 ** If the parse is successful, write the number of minutes
   11095 ** of change in p->tz and return 0.  If a parser error occurs,
   11096 ** return non-zero.
   11097 **
   11098 ** A missing specifier is not considered an error.
   11099 */
   11100 static int parseTimezone(const char *zDate, DateTime *p){
   11101   int sgn = 0;
   11102   int nHr, nMn;
   11103   int c;
   11104   while( sqlite3Isspace(*zDate) ){ zDate++; }
   11105   p->tz = 0;
   11106   c = *zDate;
   11107   if( c=='-' ){
   11108     sgn = -1;
   11109   }else if( c=='+' ){
   11110     sgn = +1;
   11111   }else if( c=='Z' || c=='z' ){
   11112     zDate++;
   11113     goto zulu_time;
   11114   }else{
   11115     return c!=0;
   11116   }
   11117   zDate++;
   11118   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
   11119     return 1;
   11120   }
   11121   zDate += 5;
   11122   p->tz = sgn*(nMn + nHr*60);
   11123 zulu_time:
   11124   while( sqlite3Isspace(*zDate) ){ zDate++; }
   11125   return *zDate!=0;
   11126 }
   11127 
   11128 /*
   11129 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   11130 ** The HH, MM, and SS must each be exactly 2 digits.  The
   11131 ** fractional seconds FFFF can be one or more digits.
   11132 **
   11133 ** Return 1 if there is a parsing error and 0 on success.
   11134 */
   11135 static int parseHhMmSs(const char *zDate, DateTime *p){
   11136   int h, m, s;
   11137   double ms = 0.0;
   11138   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
   11139     return 1;
   11140   }
   11141   zDate += 5;
   11142   if( *zDate==':' ){
   11143     zDate++;
   11144     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
   11145       return 1;
   11146     }
   11147     zDate += 2;
   11148     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   11149       double rScale = 1.0;
   11150       zDate++;
   11151       while( sqlite3Isdigit(*zDate) ){
   11152         ms = ms*10.0 + *zDate - '0';
   11153         rScale *= 10.0;
   11154         zDate++;
   11155       }
   11156       ms /= rScale;
   11157     }
   11158   }else{
   11159     s = 0;
   11160   }
   11161   p->validJD = 0;
   11162   p->validHMS = 1;
   11163   p->h = h;
   11164   p->m = m;
   11165   p->s = s + ms;
   11166   if( parseTimezone(zDate, p) ) return 1;
   11167   p->validTZ = (p->tz!=0)?1:0;
   11168   return 0;
   11169 }
   11170 
   11171 /*
   11172 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   11173 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   11174 **
   11175 ** Reference:  Meeus page 61
   11176 */
   11177 static void computeJD(DateTime *p){
   11178   int Y, M, D, A, B, X1, X2;
   11179 
   11180   if( p->validJD ) return;
   11181   if( p->validYMD ){
   11182     Y = p->Y;
   11183     M = p->M;
   11184     D = p->D;
   11185   }else{
   11186     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   11187     M = 1;
   11188     D = 1;
   11189   }
   11190   if( M<=2 ){
   11191     Y--;
   11192     M += 12;
   11193   }
   11194   A = Y/100;
   11195   B = 2 - A + (A/4);
   11196   X1 = 36525*(Y+4716)/100;
   11197   X2 = 306001*(M+1)/10000;
   11198   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   11199   p->validJD = 1;
   11200   if( p->validHMS ){
   11201     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   11202     if( p->validTZ ){
   11203       p->iJD -= p->tz*60000;
   11204       p->validYMD = 0;
   11205       p->validHMS = 0;
   11206       p->validTZ = 0;
   11207     }
   11208   }
   11209 }
   11210 
   11211 /*
   11212 ** Parse dates of the form
   11213 **
   11214 **     YYYY-MM-DD HH:MM:SS.FFF
   11215 **     YYYY-MM-DD HH:MM:SS
   11216 **     YYYY-MM-DD HH:MM
   11217 **     YYYY-MM-DD
   11218 **
   11219 ** Write the result into the DateTime structure and return 0
   11220 ** on success and 1 if the input string is not a well-formed
   11221 ** date.
   11222 */
   11223 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   11224   int Y, M, D, neg;
   11225 
   11226   if( zDate[0]=='-' ){
   11227     zDate++;
   11228     neg = 1;
   11229   }else{
   11230     neg = 0;
   11231   }
   11232   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
   11233     return 1;
   11234   }
   11235   zDate += 10;
   11236   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   11237   if( parseHhMmSs(zDate, p)==0 ){
   11238     /* We got the time */
   11239   }else if( *zDate==0 ){
   11240     p->validHMS = 0;
   11241   }else{
   11242     return 1;
   11243   }
   11244   p->validJD = 0;
   11245   p->validYMD = 1;
   11246   p->Y = neg ? -Y : Y;
   11247   p->M = M;
   11248   p->D = D;
   11249   if( p->validTZ ){
   11250     computeJD(p);
   11251   }
   11252   return 0;
   11253 }
   11254 
   11255 /*
   11256 ** Set the time to the current time reported by the VFS
   11257 */
   11258 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   11259   double r;
   11260   sqlite3 *db = sqlite3_context_db_handle(context);
   11261   sqlite3OsCurrentTime(db->pVfs, &r);
   11262   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   11263   p->validJD = 1;
   11264 }
   11265 
   11266 /*
   11267 ** Attempt to parse the given string into a Julian Day Number.  Return
   11268 ** the number of errors.
   11269 **
   11270 ** The following are acceptable forms for the input string:
   11271 **
   11272 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   11273 **      DDDD.DD
   11274 **      now
   11275 **
   11276 ** In the first form, the +/-HH:MM is always optional.  The fractional
   11277 ** seconds extension (the ".FFF") is optional.  The seconds portion
   11278 ** (":SS.FFF") is option.  The year and date can be omitted as long
   11279 ** as there is a time string.  The time string can be omitted as long
   11280 ** as there is a year and date.
   11281 */
   11282 static int parseDateOrTime(
   11283   sqlite3_context *context,
   11284   const char *zDate,
   11285   DateTime *p
   11286 ){
   11287   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
   11288   if( parseYyyyMmDd(zDate,p)==0 ){
   11289     return 0;
   11290   }else if( parseHhMmSs(zDate, p)==0 ){
   11291     return 0;
   11292   }else if( sqlite3StrICmp(zDate,"now")==0){
   11293     setDateTimeToCurrent(context, p);
   11294     return 0;
   11295   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
   11296     double r;
   11297     getValue(zDate, &r);
   11298     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   11299     p->validJD = 1;
   11300     return 0;
   11301   }
   11302   return 1;
   11303 }
   11304 
   11305 /*
   11306 ** Compute the Year, Month, and Day from the julian day number.
   11307 */
   11308 static void computeYMD(DateTime *p){
   11309   int Z, A, B, C, D, E, X1;
   11310   if( p->validYMD ) return;
   11311   if( !p->validJD ){
   11312     p->Y = 2000;
   11313     p->M = 1;
   11314     p->D = 1;
   11315   }else{
   11316     Z = (int)((p->iJD + 43200000)/86400000);
   11317     A = (int)((Z - 1867216.25)/36524.25);
   11318     A = Z + 1 + A - (A/4);
   11319     B = A + 1524;
   11320     C = (int)((B - 122.1)/365.25);
   11321     D = (36525*C)/100;
   11322     E = (int)((B-D)/30.6001);
   11323     X1 = (int)(30.6001*E);
   11324     p->D = B - D - X1;
   11325     p->M = E<14 ? E-1 : E-13;
   11326     p->Y = p->M>2 ? C - 4716 : C - 4715;
   11327   }
   11328   p->validYMD = 1;
   11329 }
   11330 
   11331 /*
   11332 ** Compute the Hour, Minute, and Seconds from the julian day number.
   11333 */
   11334 static void computeHMS(DateTime *p){
   11335   int s;
   11336   if( p->validHMS ) return;
   11337   computeJD(p);
   11338   s = (int)((p->iJD + 43200000) % 86400000);
   11339   p->s = s/1000.0;
   11340   s = (int)p->s;
   11341   p->s -= s;
   11342   p->h = s/3600;
   11343   s -= p->h*3600;
   11344   p->m = s/60;
   11345   p->s += s - p->m*60;
   11346   p->validHMS = 1;
   11347 }
   11348 
   11349 /*
   11350 ** Compute both YMD and HMS
   11351 */
   11352 static void computeYMD_HMS(DateTime *p){
   11353   computeYMD(p);
   11354   computeHMS(p);
   11355 }
   11356 
   11357 /*
   11358 ** Clear the YMD and HMS and the TZ
   11359 */
   11360 static void clearYMD_HMS_TZ(DateTime *p){
   11361   p->validYMD = 0;
   11362   p->validHMS = 0;
   11363   p->validTZ = 0;
   11364 }
   11365 
   11366 #ifndef SQLITE_OMIT_LOCALTIME
   11367 /*
   11368 ** Compute the difference (in milliseconds)
   11369 ** between localtime and UTC (a.k.a. GMT)
   11370 ** for the time value p where p is in UTC.
   11371 */
   11372 static sqlite3_int64 localtimeOffset(DateTime *p){
   11373   DateTime x, y;
   11374   time_t t;
   11375   x = *p;
   11376   computeYMD_HMS(&x);
   11377   if( x.Y<1971 || x.Y>=2038 ){
   11378     x.Y = 2000;
   11379     x.M = 1;
   11380     x.D = 1;
   11381     x.h = 0;
   11382     x.m = 0;
   11383     x.s = 0.0;
   11384   } else {
   11385     int s = (int)(x.s + 0.5);
   11386     x.s = s;
   11387   }
   11388   x.tz = 0;
   11389   x.validJD = 0;
   11390   computeJD(&x);
   11391   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   11392 #ifdef HAVE_LOCALTIME_R
   11393   {
   11394     struct tm sLocal;
   11395     localtime_r(&t, &sLocal);
   11396     y.Y = sLocal.tm_year + 1900;
   11397     y.M = sLocal.tm_mon + 1;
   11398     y.D = sLocal.tm_mday;
   11399     y.h = sLocal.tm_hour;
   11400     y.m = sLocal.tm_min;
   11401     y.s = sLocal.tm_sec;
   11402   }
   11403 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
   11404   {
   11405     struct tm sLocal;
   11406     localtime_s(&sLocal, &t);
   11407     y.Y = sLocal.tm_year + 1900;
   11408     y.M = sLocal.tm_mon + 1;
   11409     y.D = sLocal.tm_mday;
   11410     y.h = sLocal.tm_hour;
   11411     y.m = sLocal.tm_min;
   11412     y.s = sLocal.tm_sec;
   11413   }
   11414 #else
   11415   {
   11416     struct tm *pTm;
   11417     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   11418     pTm = localtime(&t);
   11419     y.Y = pTm->tm_year + 1900;
   11420     y.M = pTm->tm_mon + 1;
   11421     y.D = pTm->tm_mday;
   11422     y.h = pTm->tm_hour;
   11423     y.m = pTm->tm_min;
   11424     y.s = pTm->tm_sec;
   11425     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   11426   }
   11427 #endif
   11428   y.validYMD = 1;
   11429   y.validHMS = 1;
   11430   y.validJD = 0;
   11431   y.validTZ = 0;
   11432   computeJD(&y);
   11433   return y.iJD - x.iJD;
   11434 }
   11435 #endif /* SQLITE_OMIT_LOCALTIME */
   11436 
   11437 /*
   11438 ** Process a modifier to a date-time stamp.  The modifiers are
   11439 ** as follows:
   11440 **
   11441 **     NNN days
   11442 **     NNN hours
   11443 **     NNN minutes
   11444 **     NNN.NNNN seconds
   11445 **     NNN months
   11446 **     NNN years
   11447 **     start of month
   11448 **     start of year
   11449 **     start of week
   11450 **     start of day
   11451 **     weekday N
   11452 **     unixepoch
   11453 **     localtime
   11454 **     utc
   11455 **
   11456 ** Return 0 on success and 1 if there is any kind of error.
   11457 */
   11458 static int parseModifier(const char *zMod, DateTime *p){
   11459   int rc = 1;
   11460   int n;
   11461   double r;
   11462   char *z, zBuf[30];
   11463   z = zBuf;
   11464   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
   11465     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
   11466   }
   11467   z[n] = 0;
   11468   switch( z[0] ){
   11469 #ifndef SQLITE_OMIT_LOCALTIME
   11470     case 'l': {
   11471       /*    localtime
   11472       **
   11473       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   11474       ** show local time.
   11475       */
   11476       if( strcmp(z, "localtime")==0 ){
   11477         computeJD(p);
   11478         p->iJD += localtimeOffset(p);
   11479         clearYMD_HMS_TZ(p);
   11480         rc = 0;
   11481       }
   11482       break;
   11483     }
   11484 #endif
   11485     case 'u': {
   11486       /*
   11487       **    unixepoch
   11488       **
   11489       ** Treat the current value of p->iJD as the number of
   11490       ** seconds since 1970.  Convert to a real julian day number.
   11491       */
   11492       if( strcmp(z, "unixepoch")==0 && p->validJD ){
   11493         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
   11494         clearYMD_HMS_TZ(p);
   11495         rc = 0;
   11496       }
   11497 #ifndef SQLITE_OMIT_LOCALTIME
   11498       else if( strcmp(z, "utc")==0 ){
   11499         sqlite3_int64 c1;
   11500         computeJD(p);
   11501         c1 = localtimeOffset(p);
   11502         p->iJD -= c1;
   11503         clearYMD_HMS_TZ(p);
   11504         p->iJD += c1 - localtimeOffset(p);
   11505         rc = 0;
   11506       }
   11507 #endif
   11508       break;
   11509     }
   11510     case 'w': {
   11511       /*
   11512       **    weekday N
   11513       **
   11514       ** Move the date to the same time on the next occurrence of
   11515       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   11516       ** date is already on the appropriate weekday, this is a no-op.
   11517       */
   11518       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
   11519                  && (n=(int)r)==r && n>=0 && r<7 ){
   11520         sqlite3_int64 Z;
   11521         computeYMD_HMS(p);
   11522         p->validTZ = 0;
   11523         p->validJD = 0;
   11524         computeJD(p);
   11525         Z = ((p->iJD + 129600000)/86400000) % 7;
   11526         if( Z>n ) Z -= 7;
   11527         p->iJD += (n - Z)*86400000;
   11528         clearYMD_HMS_TZ(p);
   11529         rc = 0;
   11530       }
   11531       break;
   11532     }
   11533     case 's': {
   11534       /*
   11535       **    start of TTTTT
   11536       **
   11537       ** Move the date backwards to the beginning of the current day,
   11538       ** or month or year.
   11539       */
   11540       if( strncmp(z, "start of ", 9)!=0 ) break;
   11541       z += 9;
   11542       computeYMD(p);
   11543       p->validHMS = 1;
   11544       p->h = p->m = 0;
   11545       p->s = 0.0;
   11546       p->validTZ = 0;
   11547       p->validJD = 0;
   11548       if( strcmp(z,"month")==0 ){
   11549         p->D = 1;
   11550         rc = 0;
   11551       }else if( strcmp(z,"year")==0 ){
   11552         computeYMD(p);
   11553         p->M = 1;
   11554         p->D = 1;
   11555         rc = 0;
   11556       }else if( strcmp(z,"day")==0 ){
   11557         rc = 0;
   11558       }
   11559       break;
   11560     }
   11561     case '+':
   11562     case '-':
   11563     case '0':
   11564     case '1':
   11565     case '2':
   11566     case '3':
   11567     case '4':
   11568     case '5':
   11569     case '6':
   11570     case '7':
   11571     case '8':
   11572     case '9': {
   11573       double rRounder;
   11574       n = getValue(z, &r);
   11575       assert( n>=1 );
   11576       if( z[n]==':' ){
   11577         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   11578         ** specified number of hours, minutes, seconds, and fractional seconds
   11579         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   11580         ** omitted.
   11581         */
   11582         const char *z2 = z;
   11583         DateTime tx;
   11584         sqlite3_int64 day;
   11585         if( !sqlite3Isdigit(*z2) ) z2++;
   11586         memset(&tx, 0, sizeof(tx));
   11587         if( parseHhMmSs(z2, &tx) ) break;
   11588         computeJD(&tx);
   11589         tx.iJD -= 43200000;
   11590         day = tx.iJD/86400000;
   11591         tx.iJD -= day*86400000;
   11592         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   11593         computeJD(p);
   11594         clearYMD_HMS_TZ(p);
   11595         p->iJD += tx.iJD;
   11596         rc = 0;
   11597         break;
   11598       }
   11599       z += n;
   11600       while( sqlite3Isspace(*z) ) z++;
   11601       n = sqlite3Strlen30(z);
   11602       if( n>10 || n<3 ) break;
   11603       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
   11604       computeJD(p);
   11605       rc = 0;
   11606       rRounder = r<0 ? -0.5 : +0.5;
   11607       if( n==3 && strcmp(z,"day")==0 ){
   11608         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
   11609       }else if( n==4 && strcmp(z,"hour")==0 ){
   11610         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
   11611       }else if( n==6 && strcmp(z,"minute")==0 ){
   11612         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
   11613       }else if( n==6 && strcmp(z,"second")==0 ){
   11614         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
   11615       }else if( n==5 && strcmp(z,"month")==0 ){
   11616         int x, y;
   11617         computeYMD_HMS(p);
   11618         p->M += (int)r;
   11619         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   11620         p->Y += x;
   11621         p->M -= x*12;
   11622         p->validJD = 0;
   11623         computeJD(p);
   11624         y = (int)r;
   11625         if( y!=r ){
   11626           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
   11627         }
   11628       }else if( n==4 && strcmp(z,"year")==0 ){
   11629         int y = (int)r;
   11630         computeYMD_HMS(p);
   11631         p->Y += y;
   11632         p->validJD = 0;
   11633         computeJD(p);
   11634         if( y!=r ){
   11635           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
   11636         }
   11637       }else{
   11638         rc = 1;
   11639       }
   11640       clearYMD_HMS_TZ(p);
   11641       break;
   11642     }
   11643     default: {
   11644       break;
   11645     }
   11646   }
   11647   return rc;
   11648 }
   11649 
   11650 /*
   11651 ** Process time function arguments.  argv[0] is a date-time stamp.
   11652 ** argv[1] and following are modifiers.  Parse them all and write
   11653 ** the resulting time into the DateTime structure p.  Return 0
   11654 ** on success and 1 if there are any errors.
   11655 **
   11656 ** If there are zero parameters (if even argv[0] is undefined)
   11657 ** then assume a default value of "now" for argv[0].
   11658 */
   11659 static int isDate(
   11660   sqlite3_context *context,
   11661   int argc,
   11662   sqlite3_value **argv,
   11663   DateTime *p
   11664 ){
   11665   int i;
   11666   const unsigned char *z;
   11667   int eType;
   11668   memset(p, 0, sizeof(*p));
   11669   if( argc==0 ){
   11670     setDateTimeToCurrent(context, p);
   11671   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   11672                    || eType==SQLITE_INTEGER ){
   11673     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
   11674     p->validJD = 1;
   11675   }else{
   11676     z = sqlite3_value_text(argv[0]);
   11677     if( !z || parseDateOrTime(context, (char*)z, p) ){
   11678       return 1;
   11679     }
   11680   }
   11681   for(i=1; i<argc; i++){
   11682     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
   11683       return 1;
   11684     }
   11685   }
   11686   return 0;
   11687 }
   11688 
   11689 
   11690 /*
   11691 ** The following routines implement the various date and time functions
   11692 ** of SQLite.
   11693 */
   11694 
   11695 /*
   11696 **    julianday( TIMESTRING, MOD, MOD, ...)
   11697 **
   11698 ** Return the julian day number of the date specified in the arguments
   11699 */
   11700 static void juliandayFunc(
   11701   sqlite3_context *context,
   11702   int argc,
   11703   sqlite3_value **argv
   11704 ){
   11705   DateTime x;
   11706   if( isDate(context, argc, argv, &x)==0 ){
   11707     computeJD(&x);
   11708     sqlite3_result_double(context, x.iJD/86400000.0);
   11709   }
   11710 }
   11711 
   11712 /*
   11713 **    datetime( TIMESTRING, MOD, MOD, ...)
   11714 **
   11715 ** Return YYYY-MM-DD HH:MM:SS
   11716 */
   11717 static void datetimeFunc(
   11718   sqlite3_context *context,
   11719   int argc,
   11720   sqlite3_value **argv
   11721 ){
   11722   DateTime x;
   11723   if( isDate(context, argc, argv, &x)==0 ){
   11724     char zBuf[100];
   11725     computeYMD_HMS(&x);
   11726     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   11727                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   11728     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11729   }
   11730 }
   11731 
   11732 /*
   11733 **    time( TIMESTRING, MOD, MOD, ...)
   11734 **
   11735 ** Return HH:MM:SS
   11736 */
   11737 static void timeFunc(
   11738   sqlite3_context *context,
   11739   int argc,
   11740   sqlite3_value **argv
   11741 ){
   11742   DateTime x;
   11743   if( isDate(context, argc, argv, &x)==0 ){
   11744     char zBuf[100];
   11745     computeHMS(&x);
   11746     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   11747     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11748   }
   11749 }
   11750 
   11751 /*
   11752 **    date( TIMESTRING, MOD, MOD, ...)
   11753 **
   11754 ** Return YYYY-MM-DD
   11755 */
   11756 static void dateFunc(
   11757   sqlite3_context *context,
   11758   int argc,
   11759   sqlite3_value **argv
   11760 ){
   11761   DateTime x;
   11762   if( isDate(context, argc, argv, &x)==0 ){
   11763     char zBuf[100];
   11764     computeYMD(&x);
   11765     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   11766     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11767   }
   11768 }
   11769 
   11770 /*
   11771 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   11772 **
   11773 ** Return a string described by FORMAT.  Conversions as follows:
   11774 **
   11775 **   %d  day of month
   11776 **   %f  ** fractional seconds  SS.SSS
   11777 **   %H  hour 00-24
   11778 **   %j  day of year 000-366
   11779 **   %J  ** Julian day number
   11780 **   %m  month 01-12
   11781 **   %M  minute 00-59
   11782 **   %s  seconds since 1970-01-01
   11783 **   %S  seconds 00-59
   11784 **   %w  day of week 0-6  sunday==0
   11785 **   %W  week of year 00-53
   11786 **   %Y  year 0000-9999
   11787 **   %%  %
   11788 */
   11789 static void strftimeFunc(
   11790   sqlite3_context *context,
   11791   int argc,
   11792   sqlite3_value **argv
   11793 ){
   11794   DateTime x;
   11795   u64 n;
   11796   size_t i,j;
   11797   char *z;
   11798   sqlite3 *db;
   11799   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   11800   char zBuf[100];
   11801   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   11802   db = sqlite3_context_db_handle(context);
   11803   for(i=0, n=1; zFmt[i]; i++, n++){
   11804     if( zFmt[i]=='%' ){
   11805       switch( zFmt[i+1] ){
   11806         case 'd':
   11807         case 'H':
   11808         case 'm':
   11809         case 'M':
   11810         case 'S':
   11811         case 'W':
   11812           n++;
   11813           /* fall thru */
   11814         case 'w':
   11815         case '%':
   11816           break;
   11817         case 'f':
   11818           n += 8;
   11819           break;
   11820         case 'j':
   11821           n += 3;
   11822           break;
   11823         case 'Y':
   11824           n += 8;
   11825           break;
   11826         case 's':
   11827         case 'J':
   11828           n += 50;
   11829           break;
   11830         default:
   11831           return;  /* ERROR.  return a NULL */
   11832       }
   11833       i++;
   11834     }
   11835   }
   11836   testcase( n==sizeof(zBuf)-1 );
   11837   testcase( n==sizeof(zBuf) );
   11838   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   11839   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   11840   if( n<sizeof(zBuf) ){
   11841     z = zBuf;
   11842   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   11843     sqlite3_result_error_toobig(context);
   11844     return;
   11845   }else{
   11846     z = sqlite3DbMallocRaw(db, (int)n);
   11847     if( z==0 ){
   11848       sqlite3_result_error_nomem(context);
   11849       return;
   11850     }
   11851   }
   11852   computeJD(&x);
   11853   computeYMD_HMS(&x);
   11854   for(i=j=0; zFmt[i]; i++){
   11855     if( zFmt[i]!='%' ){
   11856       z[j++] = zFmt[i];
   11857     }else{
   11858       i++;
   11859       switch( zFmt[i] ){
   11860         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   11861         case 'f': {
   11862           double s = x.s;
   11863           if( s>59.999 ) s = 59.999;
   11864           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   11865           j += sqlite3Strlen30(&z[j]);
   11866           break;
   11867         }
   11868         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   11869         case 'W': /* Fall thru */
   11870         case 'j': {
   11871           int nDay;             /* Number of days since 1st day of year */
   11872           DateTime y = x;
   11873           y.validJD = 0;
   11874           y.M = 1;
   11875           y.D = 1;
   11876           computeJD(&y);
   11877           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   11878           if( zFmt[i]=='W' ){
   11879             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   11880             wd = (int)(((x.iJD+43200000)/86400000)%7);
   11881             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   11882             j += 2;
   11883           }else{
   11884             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   11885             j += 3;
   11886           }
   11887           break;
   11888         }
   11889         case 'J': {
   11890           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   11891           j+=sqlite3Strlen30(&z[j]);
   11892           break;
   11893         }
   11894         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   11895         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   11896         case 's': {
   11897           sqlite3_snprintf(30,&z[j],"%lld",
   11898                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   11899           j += sqlite3Strlen30(&z[j]);
   11900           break;
   11901         }
   11902         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   11903         case 'w': {
   11904           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   11905           break;
   11906         }
   11907         case 'Y': {
   11908           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   11909           break;
   11910         }
   11911         default:   z[j++] = '%'; break;
   11912       }
   11913     }
   11914   }
   11915   z[j] = 0;
   11916   sqlite3_result_text(context, z, -1,
   11917                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   11918 }
   11919 
   11920 /*
   11921 ** current_time()
   11922 **
   11923 ** This function returns the same value as time('now').
   11924 */
   11925 static void ctimeFunc(
   11926   sqlite3_context *context,
   11927   int NotUsed,
   11928   sqlite3_value **NotUsed2
   11929 ){
   11930   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11931   timeFunc(context, 0, 0);
   11932 }
   11933 
   11934 /*
   11935 ** current_date()
   11936 **
   11937 ** This function returns the same value as date('now').
   11938 */
   11939 static void cdateFunc(
   11940   sqlite3_context *context,
   11941   int NotUsed,
   11942   sqlite3_value **NotUsed2
   11943 ){
   11944   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11945   dateFunc(context, 0, 0);
   11946 }
   11947 
   11948 /*
   11949 ** current_timestamp()
   11950 **
   11951 ** This function returns the same value as datetime('now').
   11952 */
   11953 static void ctimestampFunc(
   11954   sqlite3_context *context,
   11955   int NotUsed,
   11956   sqlite3_value **NotUsed2
   11957 ){
   11958   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11959   datetimeFunc(context, 0, 0);
   11960 }
   11961 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   11962 
   11963 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   11964 /*
   11965 ** If the library is compiled to omit the full-scale date and time
   11966 ** handling (to get a smaller binary), the following minimal version
   11967 ** of the functions current_time(), current_date() and current_timestamp()
   11968 ** are included instead. This is to support column declarations that
   11969 ** include "DEFAULT CURRENT_TIME" etc.
   11970 **
   11971 ** This function uses the C-library functions time(), gmtime()
   11972 ** and strftime(). The format string to pass to strftime() is supplied
   11973 ** as the user-data for the function.
   11974 */
   11975 static void currentTimeFunc(
   11976   sqlite3_context *context,
   11977   int argc,
   11978   sqlite3_value **argv
   11979 ){
   11980   time_t t;
   11981   char *zFormat = (char *)sqlite3_user_data(context);
   11982   sqlite3 *db;
   11983   double rT;
   11984   char zBuf[20];
   11985 
   11986   UNUSED_PARAMETER(argc);
   11987   UNUSED_PARAMETER(argv);
   11988 
   11989   db = sqlite3_context_db_handle(context);
   11990   sqlite3OsCurrentTime(db->pVfs, &rT);
   11991 #ifndef SQLITE_OMIT_FLOATING_POINT
   11992   t = 86400.0*(rT - 2440587.5) + 0.5;
   11993 #else
   11994   /* without floating point support, rT will have
   11995   ** already lost fractional day precision.
   11996   */
   11997   t = 86400 * (rT - 2440587) - 43200;
   11998 #endif
   11999 #ifdef HAVE_GMTIME_R
   12000   {
   12001     struct tm sNow;
   12002     gmtime_r(&t, &sNow);
   12003     strftime(zBuf, 20, zFormat, &sNow);
   12004   }
   12005 #else
   12006   {
   12007     struct tm *pTm;
   12008     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   12009     pTm = gmtime(&t);
   12010     strftime(zBuf, 20, zFormat, pTm);
   12011     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   12012   }
   12013 #endif
   12014 
   12015   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   12016 }
   12017 #endif
   12018 
   12019 /*
   12020 ** This function registered all of the above C functions as SQL
   12021 ** functions.  This should be the only routine in this file with
   12022 ** external linkage.
   12023 */
   12024 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   12025   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
   12026 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   12027     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
   12028     FUNCTION(date,             -1, 0, 0, dateFunc      ),
   12029     FUNCTION(time,             -1, 0, 0, timeFunc      ),
   12030     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
   12031     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
   12032     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   12033     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   12034     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   12035 #else
   12036     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   12037     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
   12038     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   12039 #endif
   12040   };
   12041   int i;
   12042   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   12043   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
   12044 
   12045   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
   12046     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   12047   }
   12048 }
   12049 
   12050 /************** End of date.c ************************************************/
   12051 /************** Begin file os.c **********************************************/
   12052 /*
   12053 ** 2005 November 29
   12054 **
   12055 ** The author disclaims copyright to this source code.  In place of
   12056 ** a legal notice, here is a blessing:
   12057 **
   12058 **    May you do good and not evil.
   12059 **    May you find forgiveness for yourself and forgive others.
   12060 **    May you share freely, never taking more than you give.
   12061 **
   12062 ******************************************************************************
   12063 **
   12064 ** This file contains OS interface code that is common to all
   12065 ** architectures.
   12066 */
   12067 #define _SQLITE_OS_C_ 1
   12068 #undef _SQLITE_OS_C_
   12069 
   12070 /*
   12071 ** The default SQLite sqlite3_vfs implementations do not allocate
   12072 ** memory (actually, os_unix.c allocates a small amount of memory
   12073 ** from within OsOpen()), but some third-party implementations may.
   12074 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   12075 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   12076 **
   12077 ** The following functions are instrumented for malloc() failure
   12078 ** testing:
   12079 **
   12080 **     sqlite3OsOpen()
   12081 **     sqlite3OsRead()
   12082 **     sqlite3OsWrite()
   12083 **     sqlite3OsSync()
   12084 **     sqlite3OsLock()
   12085 **
   12086 */
   12087 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
   12088   #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
   12089     void *pTstAlloc = sqlite3Malloc(10);                             \
   12090     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
   12091     sqlite3_free(pTstAlloc);                                         \
   12092   }
   12093 #else
   12094   #define DO_OS_MALLOC_TEST(x)
   12095 #endif
   12096 
   12097 /*
   12098 ** The following routines are convenience wrappers around methods
   12099 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   12100 ** of this would be completely automatic if SQLite were coded using
   12101 ** C++ instead of plain old C.
   12102 */
   12103 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
   12104   int rc = SQLITE_OK;
   12105   if( pId->pMethods ){
   12106     rc = pId->pMethods->xClose(pId);
   12107     pId->pMethods = 0;
   12108   }
   12109   return rc;
   12110 }
   12111 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   12112   DO_OS_MALLOC_TEST(id);
   12113   return id->pMethods->xRead(id, pBuf, amt, offset);
   12114 }
   12115 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   12116   DO_OS_MALLOC_TEST(id);
   12117   return id->pMethods->xWrite(id, pBuf, amt, offset);
   12118 }
   12119 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   12120   return id->pMethods->xTruncate(id, size);
   12121 }
   12122 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   12123   DO_OS_MALLOC_TEST(id);
   12124   return id->pMethods->xSync(id, flags);
   12125 }
   12126 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   12127   DO_OS_MALLOC_TEST(id);
   12128   return id->pMethods->xFileSize(id, pSize);
   12129 }
   12130 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   12131   DO_OS_MALLOC_TEST(id);
   12132   return id->pMethods->xLock(id, lockType);
   12133 }
   12134 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   12135   return id->pMethods->xUnlock(id, lockType);
   12136 }
   12137 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   12138   DO_OS_MALLOC_TEST(id);
   12139   return id->pMethods->xCheckReservedLock(id, pResOut);
   12140 }
   12141 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   12142   return id->pMethods->xFileControl(id, op, pArg);
   12143 }
   12144 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   12145   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   12146   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   12147 }
   12148 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   12149   return id->pMethods->xDeviceCharacteristics(id);
   12150 }
   12151 
   12152 /*
   12153 ** The next group of routines are convenience wrappers around the
   12154 ** VFS methods.
   12155 */
   12156 SQLITE_PRIVATE int sqlite3OsOpen(
   12157   sqlite3_vfs *pVfs,
   12158   const char *zPath,
   12159   sqlite3_file *pFile,
   12160   int flags,
   12161   int *pFlagsOut
   12162 ){
   12163   int rc;
   12164   DO_OS_MALLOC_TEST(0);
   12165   /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   12166   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   12167   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   12168   ** reaching the VFS. */
   12169   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
   12170   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   12171   return rc;
   12172 }
   12173 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   12174   return pVfs->xDelete(pVfs, zPath, dirSync);
   12175 }
   12176 SQLITE_PRIVATE int sqlite3OsAccess(
   12177   sqlite3_vfs *pVfs,
   12178   const char *zPath,
   12179   int flags,
   12180   int *pResOut
   12181 ){
   12182   DO_OS_MALLOC_TEST(0);
   12183   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   12184 }
   12185 SQLITE_PRIVATE int sqlite3OsFullPathname(
   12186   sqlite3_vfs *pVfs,
   12187   const char *zPath,
   12188   int nPathOut,
   12189   char *zPathOut
   12190 ){
   12191   zPathOut[0] = 0;
   12192   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   12193 }
   12194 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   12195 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   12196   return pVfs->xDlOpen(pVfs, zPath);
   12197 }
   12198 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   12199   pVfs->xDlError(pVfs, nByte, zBufOut);
   12200 }
   12201 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   12202   return pVfs->xDlSym(pVfs, pHdle, zSym);
   12203 }
   12204 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   12205   pVfs->xDlClose(pVfs, pHandle);
   12206 }
   12207 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   12208 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   12209   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   12210 }
   12211 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   12212   return pVfs->xSleep(pVfs, nMicro);
   12213 }
   12214 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   12215   return pVfs->xCurrentTime(pVfs, pTimeOut);
   12216 }
   12217 
   12218 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   12219   sqlite3_vfs *pVfs,
   12220   const char *zFile,
   12221   sqlite3_file **ppFile,
   12222   int flags,
   12223   int *pOutFlags
   12224 ){
   12225   int rc = SQLITE_NOMEM;
   12226   sqlite3_file *pFile;
   12227   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
   12228   if( pFile ){
   12229     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   12230     if( rc!=SQLITE_OK ){
   12231       sqlite3_free(pFile);
   12232     }else{
   12233       *ppFile = pFile;
   12234     }
   12235   }
   12236   return rc;
   12237 }
   12238 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
   12239   int rc = SQLITE_OK;
   12240   assert( pFile );
   12241   rc = sqlite3OsClose(pFile);
   12242   sqlite3_free(pFile);
   12243   return rc;
   12244 }
   12245 
   12246 /*
   12247 ** This function is a wrapper around the OS specific implementation of
   12248 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   12249 ** ability to simulate a malloc failure, so that the handling of an
   12250 ** error in sqlite3_os_init() by the upper layers can be tested.
   12251 */
   12252 SQLITE_PRIVATE int sqlite3OsInit(void){
   12253   void *p = sqlite3_malloc(10);
   12254   if( p==0 ) return SQLITE_NOMEM;
   12255   sqlite3_free(p);
   12256   return sqlite3_os_init();
   12257 }
   12258 
   12259 /*
   12260 ** The list of all registered VFS implementations.
   12261 */
   12262 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   12263 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   12264 
   12265 /*
   12266 ** Locate a VFS by name.  If no name is given, simply return the
   12267 ** first VFS on the list.
   12268 */
   12269 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   12270   sqlite3_vfs *pVfs = 0;
   12271 #if SQLITE_THREADSAFE
   12272   sqlite3_mutex *mutex;
   12273 #endif
   12274 #ifndef SQLITE_OMIT_AUTOINIT
   12275   int rc = sqlite3_initialize();
   12276   if( rc ) return 0;
   12277 #endif
   12278 #if SQLITE_THREADSAFE
   12279   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12280 #endif
   12281   sqlite3_mutex_enter(mutex);
   12282   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   12283     if( zVfs==0 ) break;
   12284     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   12285   }
   12286   sqlite3_mutex_leave(mutex);
   12287   return pVfs;
   12288 }
   12289 
   12290 /*
   12291 ** Unlink a VFS from the linked list
   12292 */
   12293 static void vfsUnlink(sqlite3_vfs *pVfs){
   12294   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   12295   if( pVfs==0 ){
   12296     /* No-op */
   12297   }else if( vfsList==pVfs ){
   12298     vfsList = pVfs->pNext;
   12299   }else if( vfsList ){
   12300     sqlite3_vfs *p = vfsList;
   12301     while( p->pNext && p->pNext!=pVfs ){
   12302       p = p->pNext;
   12303     }
   12304     if( p->pNext==pVfs ){
   12305       p->pNext = pVfs->pNext;
   12306     }
   12307   }
   12308 }
   12309 
   12310 /*
   12311 ** Register a VFS with the system.  It is harmless to register the same
   12312 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   12313 ** true.
   12314 */
   12315 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   12316   sqlite3_mutex *mutex = 0;
   12317 #ifndef SQLITE_OMIT_AUTOINIT
   12318   int rc = sqlite3_initialize();
   12319   if( rc ) return rc;
   12320 #endif
   12321   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12322   sqlite3_mutex_enter(mutex);
   12323   vfsUnlink(pVfs);
   12324   if( makeDflt || vfsList==0 ){
   12325     pVfs->pNext = vfsList;
   12326     vfsList = pVfs;
   12327   }else{
   12328     pVfs->pNext = vfsList->pNext;
   12329     vfsList->pNext = pVfs;
   12330   }
   12331   assert(vfsList);
   12332   sqlite3_mutex_leave(mutex);
   12333   return SQLITE_OK;
   12334 }
   12335 
   12336 /*
   12337 ** Unregister a VFS so that it is no longer accessible.
   12338 */
   12339 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   12340 #if SQLITE_THREADSAFE
   12341   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12342 #endif
   12343   sqlite3_mutex_enter(mutex);
   12344   vfsUnlink(pVfs);
   12345   sqlite3_mutex_leave(mutex);
   12346   return SQLITE_OK;
   12347 }
   12348 
   12349 /************** End of os.c **************************************************/
   12350 /************** Begin file fault.c *******************************************/
   12351 /*
   12352 ** 2008 Jan 22
   12353 **
   12354 ** The author disclaims copyright to this source code.  In place of
   12355 ** a legal notice, here is a blessing:
   12356 **
   12357 **    May you do good and not evil.
   12358 **    May you find forgiveness for yourself and forgive others.
   12359 **    May you share freely, never taking more than you give.
   12360 **
   12361 *************************************************************************
   12362 **
   12363 ** This file contains code to support the concept of "benign"
   12364 ** malloc failures (when the xMalloc() or xRealloc() method of the
   12365 ** sqlite3_mem_methods structure fails to allocate a block of memory
   12366 ** and returns 0).
   12367 **
   12368 ** Most malloc failures are non-benign. After they occur, SQLite
   12369 ** abandons the current operation and returns an error code (usually
   12370 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   12371 ** fatal. For example, if a malloc fails while resizing a hash table, this
   12372 ** is completely recoverable simply by not carrying out the resize. The
   12373 ** hash table will continue to function normally.  So a malloc failure
   12374 ** during a hash table resize is a benign fault.
   12375 */
   12376 
   12377 
   12378 #ifndef SQLITE_OMIT_BUILTIN_TEST
   12379 
   12380 /*
   12381 ** Global variables.
   12382 */
   12383 typedef struct BenignMallocHooks BenignMallocHooks;
   12384 static SQLITE_WSD struct BenignMallocHooks {
   12385   void (*xBenignBegin)(void);
   12386   void (*xBenignEnd)(void);
   12387 } sqlite3Hooks = { 0, 0 };
   12388 
   12389 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   12390 ** structure.  If writable static data is unsupported on the target,
   12391 ** we have to locate the state vector at run-time.  In the more common
   12392 ** case where writable static data is supported, wsdHooks can refer directly
   12393 ** to the "sqlite3Hooks" state vector declared above.
   12394 */
   12395 #ifdef SQLITE_OMIT_WSD
   12396 # define wsdHooksInit \
   12397   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   12398 # define wsdHooks x[0]
   12399 #else
   12400 # define wsdHooksInit
   12401 # define wsdHooks sqlite3Hooks
   12402 #endif
   12403 
   12404 
   12405 /*
   12406 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   12407 ** sqlite3EndBenignMalloc() are called, respectively.
   12408 */
   12409 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   12410   void (*xBenignBegin)(void),
   12411   void (*xBenignEnd)(void)
   12412 ){
   12413   wsdHooksInit;
   12414   wsdHooks.xBenignBegin = xBenignBegin;
   12415   wsdHooks.xBenignEnd = xBenignEnd;
   12416 }
   12417 
   12418 /*
   12419 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   12420 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   12421 ** indicates that subsequent malloc failures are non-benign.
   12422 */
   12423 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   12424   wsdHooksInit;
   12425   if( wsdHooks.xBenignBegin ){
   12426     wsdHooks.xBenignBegin();
   12427   }
   12428 }
   12429 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   12430   wsdHooksInit;
   12431   if( wsdHooks.xBenignEnd ){
   12432     wsdHooks.xBenignEnd();
   12433   }
   12434 }
   12435 
   12436 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
   12437 
   12438 /************** End of fault.c ***********************************************/
   12439 /************** Begin file mem0.c ********************************************/
   12440 /*
   12441 ** 2008 October 28
   12442 **
   12443 ** The author disclaims copyright to this source code.  In place of
   12444 ** a legal notice, here is a blessing:
   12445 **
   12446 **    May you do good and not evil.
   12447 **    May you find forgiveness for yourself and forgive others.
   12448 **    May you share freely, never taking more than you give.
   12449 **
   12450 *************************************************************************
   12451 **
   12452 ** This file contains a no-op memory allocation drivers for use when
   12453 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   12454 ** here always fail.  SQLite will not operate with these drivers.  These
   12455 ** are merely placeholders.  Real drivers must be substituted using
   12456 ** sqlite3_config() before SQLite will operate.
   12457 */
   12458 
   12459 /*
   12460 ** This version of the memory allocator is the default.  It is
   12461 ** used when no other memory allocator is specified using compile-time
   12462 ** macros.
   12463 */
   12464 #ifdef SQLITE_ZERO_MALLOC
   12465 
   12466 /*
   12467 ** No-op versions of all memory allocation routines
   12468 */
   12469 static void *sqlite3MemMalloc(int nByte){ return 0; }
   12470 static void sqlite3MemFree(void *pPrior){ return; }
   12471 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   12472 static int sqlite3MemSize(void *pPrior){ return 0; }
   12473 static int sqlite3MemRoundup(int n){ return n; }
   12474 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   12475 static void sqlite3MemShutdown(void *NotUsed){ return; }
   12476 
   12477 /*
   12478 ** This routine is the only routine in this file with external linkage.
   12479 **
   12480 ** Populate the low-level memory allocation function pointers in
   12481 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   12482 */
   12483 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   12484   static const sqlite3_mem_methods defaultMethods = {
   12485      sqlite3MemMalloc,
   12486      sqlite3MemFree,
   12487      sqlite3MemRealloc,
   12488      sqlite3MemSize,
   12489      sqlite3MemRoundup,
   12490      sqlite3MemInit,
   12491      sqlite3MemShutdown,
   12492      0
   12493   };
   12494   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   12495 }
   12496 
   12497 #endif /* SQLITE_ZERO_MALLOC */
   12498 
   12499 /************** End of mem0.c ************************************************/
   12500 /************** Begin file mem1.c ********************************************/
   12501 /*
   12502 ** 2007 August 14
   12503 **
   12504 ** The author disclaims copyright to this source code.  In place of
   12505 ** a legal notice, here is a blessing:
   12506 **
   12507 **    May you do good and not evil.
   12508 **    May you find forgiveness for yourself and forgive others.
   12509 **    May you share freely, never taking more than you give.
   12510 **
   12511 *************************************************************************
   12512 **
   12513 ** This file contains low-level memory allocation drivers for when
   12514 ** SQLite will use the standard C-library malloc/realloc/free interface
   12515 ** to obtain the memory it needs.
   12516 **
   12517 ** This file contains implementations of the low-level memory allocation
   12518 ** routines specified in the sqlite3_mem_methods object.
   12519 */
   12520 
   12521 /*
   12522 ** This version of the memory allocator is the default.  It is
   12523 ** used when no other memory allocator is specified using compile-time
   12524 ** macros.
   12525 */
   12526 #ifdef SQLITE_SYSTEM_MALLOC
   12527 
   12528 /*
   12529 ** Like malloc(), but remember the size of the allocation
   12530 ** so that we can find it later using sqlite3MemSize().
   12531 **
   12532 ** For this low-level routine, we are guaranteed that nByte>0 because
   12533 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   12534 ** routines.
   12535 */
   12536 static void *sqlite3MemMalloc(int nByte){
   12537   sqlite3_int64 *p;
   12538   assert( nByte>0 );
   12539   nByte = ROUND8(nByte);
   12540   p = malloc( nByte+8 );
   12541   if( p ){
   12542     p[0] = nByte;
   12543     p++;
   12544   }else{
   12545     testcase( sqlite3GlobalConfig.xLog!=0 );
   12546     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   12547   }
   12548   return (void *)p;
   12549 }
   12550 
   12551 /*
   12552 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   12553 ** or sqlite3MemRealloc().
   12554 **
   12555 ** For this low-level routine, we already know that pPrior!=0 since
   12556 ** cases where pPrior==0 will have been intecepted and dealt with
   12557 ** by higher-level routines.
   12558 */
   12559 static void sqlite3MemFree(void *pPrior){
   12560   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   12561   assert( pPrior!=0 );
   12562   p--;
   12563   free(p);
   12564 }
   12565 
   12566 /*
   12567 ** Report the allocated size of a prior return from xMalloc()
   12568 ** or xRealloc().
   12569 */
   12570 static int sqlite3MemSize(void *pPrior){
   12571   sqlite3_int64 *p;
   12572   if( pPrior==0 ) return 0;
   12573   p = (sqlite3_int64*)pPrior;
   12574   p--;
   12575   return (int)p[0];
   12576 }
   12577 
   12578 /*
   12579 ** Like realloc().  Resize an allocation previously obtained from
   12580 ** sqlite3MemMalloc().
   12581 **
   12582 ** For this low-level interface, we know that pPrior!=0.  Cases where
   12583 ** pPrior==0 while have been intercepted by higher-level routine and
   12584 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
   12585 ** cases where nByte<=0 will have been intercepted by higher-level
   12586 ** routines and redirected to xFree.
   12587 */
   12588 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   12589   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   12590   assert( pPrior!=0 && nByte>0 );
   12591   nByte = ROUND8(nByte);
   12592   p = (sqlite3_int64*)pPrior;
   12593   p--;
   12594   p = realloc(p, nByte+8 );
   12595   if( p ){
   12596     p[0] = nByte;
   12597     p++;
   12598   }else{
   12599     testcase( sqlite3GlobalConfig.xLog!=0 );
   12600     sqlite3_log(SQLITE_NOMEM,
   12601       "failed memory resize %u to %u bytes",
   12602       sqlite3MemSize(pPrior), nByte);
   12603   }
   12604   return (void*)p;
   12605 }
   12606 
   12607 /*
   12608 ** Round up a request size to the next valid allocation size.
   12609 */
   12610 static int sqlite3MemRoundup(int n){
   12611   return ROUND8(n);
   12612 }
   12613 
   12614 /*
   12615 ** Initialize this module.
   12616 */
   12617 static int sqlite3MemInit(void *NotUsed){
   12618   UNUSED_PARAMETER(NotUsed);
   12619   return SQLITE_OK;
   12620 }
   12621 
   12622 /*
   12623 ** Deinitialize this module.
   12624 */
   12625 static void sqlite3MemShutdown(void *NotUsed){
   12626   UNUSED_PARAMETER(NotUsed);
   12627   return;
   12628 }
   12629 
   12630 /*
   12631 ** This routine is the only routine in this file with external linkage.
   12632 **
   12633 ** Populate the low-level memory allocation function pointers in
   12634 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   12635 */
   12636 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   12637   static const sqlite3_mem_methods defaultMethods = {
   12638      sqlite3MemMalloc,
   12639      sqlite3MemFree,
   12640      sqlite3MemRealloc,
   12641      sqlite3MemSize,
   12642      sqlite3MemRoundup,
   12643      sqlite3MemInit,
   12644      sqlite3MemShutdown,
   12645      0
   12646   };
   12647   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   12648 }
   12649 
   12650 #endif /* SQLITE_SYSTEM_MALLOC */
   12651 
   12652 /************** End of mem1.c ************************************************/
   12653 /************** Begin file mem2.c ********************************************/
   12654 /*
   12655 ** 2007 August 15
   12656 **
   12657 ** The author disclaims copyright to this source code.  In place of
   12658 ** a legal notice, here is a blessing:
   12659 **
   12660 **    May you do good and not evil.
   12661 **    May you find forgiveness for yourself and forgive others.
   12662 **    May you share freely, never taking more than you give.
   12663 **
   12664 *************************************************************************
   12665 **
   12666 ** This file contains low-level memory allocation drivers for when
   12667 ** SQLite will use the standard C-library malloc/realloc/free interface
   12668 ** to obtain the memory it needs while adding lots of additional debugging
   12669 ** information to each allocation in order to help detect and fix memory
   12670 ** leaks and memory usage errors.
   12671 **
   12672 ** This file contains implementations of the low-level memory allocation
   12673 ** routines specified in the sqlite3_mem_methods object.
   12674 */
   12675 
   12676 /*
   12677 ** This version of the memory allocator is used only if the
   12678 ** SQLITE_MEMDEBUG macro is defined
   12679 */
   12680 #ifdef SQLITE_MEMDEBUG
   12681 
   12682 /*
   12683 ** The backtrace functionality is only available with GLIBC
   12684 */
   12685 #ifdef __GLIBC__
   12686   extern int backtrace(void**,int);
   12687   extern void backtrace_symbols_fd(void*const*,int,int);
   12688 #else
   12689 # define backtrace(A,B) 1
   12690 # define backtrace_symbols_fd(A,B,C)
   12691 #endif
   12692 
   12693 /*
   12694 ** Each memory allocation looks like this:
   12695 **
   12696 **  ------------------------------------------------------------------------
   12697 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   12698 **  ------------------------------------------------------------------------
   12699 **
   12700 ** The application code sees only a pointer to the allocation.  We have
   12701 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   12702 ** MemBlockHdr tells us the size of the allocation and the number of
   12703 ** backtrace pointers.  There is also a guard word at the end of the
   12704 ** MemBlockHdr.
   12705 */
   12706 struct MemBlockHdr {
   12707   i64 iSize;                          /* Size of this allocation */
   12708   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   12709   char nBacktrace;                    /* Number of backtraces on this alloc */
   12710   char nBacktraceSlots;               /* Available backtrace slots */
   12711   short nTitle;                       /* Bytes of title; includes '\0' */
   12712   int iForeGuard;                     /* Guard word for sanity */
   12713 };
   12714 
   12715 /*
   12716 ** Guard words
   12717 */
   12718 #define FOREGUARD 0x80F5E153
   12719 #define REARGUARD 0xE4676B53
   12720 
   12721 /*
   12722 ** Number of malloc size increments to track.
   12723 */
   12724 #define NCSIZE  1000
   12725 
   12726 /*
   12727 ** All of the static variables used by this module are collected
   12728 ** into a single structure named "mem".  This is to keep the
   12729 ** static variables organized and to reduce namespace pollution
   12730 ** when this module is combined with other in the amalgamation.
   12731 */
   12732 static struct {
   12733 
   12734   /*
   12735   ** Mutex to control access to the memory allocation subsystem.
   12736   */
   12737   sqlite3_mutex *mutex;
   12738 
   12739   /*
   12740   ** Head and tail of a linked list of all outstanding allocations
   12741   */
   12742   struct MemBlockHdr *pFirst;
   12743   struct MemBlockHdr *pLast;
   12744 
   12745   /*
   12746   ** The number of levels of backtrace to save in new allocations.
   12747   */
   12748   int nBacktrace;
   12749   void (*xBacktrace)(int, int, void **);
   12750 
   12751   /*
   12752   ** Title text to insert in front of each block
   12753   */
   12754   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   12755   char zTitle[100];  /* The title text */
   12756 
   12757   /*
   12758   ** sqlite3MallocDisallow() increments the following counter.
   12759   ** sqlite3MallocAllow() decrements it.
   12760   */
   12761   int disallow; /* Do not allow memory allocation */
   12762 
   12763   /*
   12764   ** Gather statistics on the sizes of memory allocations.
   12765   ** nAlloc[i] is the number of allocation attempts of i*8
   12766   ** bytes.  i==NCSIZE is the number of allocation attempts for
   12767   ** sizes more than NCSIZE*8 bytes.
   12768   */
   12769   int nAlloc[NCSIZE];      /* Total number of allocations */
   12770   int nCurrent[NCSIZE];    /* Current number of allocations */
   12771   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   12772 
   12773 } mem;
   12774 
   12775 
   12776 /*
   12777 ** Adjust memory usage statistics
   12778 */
   12779 static void adjustStats(int iSize, int increment){
   12780   int i = ROUND8(iSize)/8;
   12781   if( i>NCSIZE-1 ){
   12782     i = NCSIZE - 1;
   12783   }
   12784   if( increment>0 ){
   12785     mem.nAlloc[i]++;
   12786     mem.nCurrent[i]++;
   12787     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   12788       mem.mxCurrent[i] = mem.nCurrent[i];
   12789     }
   12790   }else{
   12791     mem.nCurrent[i]--;
   12792     assert( mem.nCurrent[i]>=0 );
   12793   }
   12794 }
   12795 
   12796 /*
   12797 ** Given an allocation, find the MemBlockHdr for that allocation.
   12798 **
   12799 ** This routine checks the guards at either end of the allocation and
   12800 ** if they are incorrect it asserts.
   12801 */
   12802 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   12803   struct MemBlockHdr *p;
   12804   int *pInt;
   12805   u8 *pU8;
   12806   int nReserve;
   12807 
   12808   p = (struct MemBlockHdr*)pAllocation;
   12809   p--;
   12810   assert( p->iForeGuard==(int)FOREGUARD );
   12811   nReserve = ROUND8(p->iSize);
   12812   pInt = (int*)pAllocation;
   12813   pU8 = (u8*)pAllocation;
   12814   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   12815   /* This checks any of the "extra" bytes allocated due
   12816   ** to rounding up to an 8 byte boundary to ensure
   12817   ** they haven't been overwritten.
   12818   */
   12819   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   12820   return p;
   12821 }
   12822 
   12823 /*
   12824 ** Return the number of bytes currently allocated at address p.
   12825 */
   12826 static int sqlite3MemSize(void *p){
   12827   struct MemBlockHdr *pHdr;
   12828   if( !p ){
   12829     return 0;
   12830   }
   12831   pHdr = sqlite3MemsysGetHeader(p);
   12832   return pHdr->iSize;
   12833 }
   12834 
   12835 /*
   12836 ** Initialize the memory allocation subsystem.
   12837 */
   12838 static int sqlite3MemInit(void *NotUsed){
   12839   UNUSED_PARAMETER(NotUsed);
   12840   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   12841   if( !sqlite3GlobalConfig.bMemstat ){
   12842     /* If memory status is enabled, then the malloc.c wrapper will already
   12843     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   12844     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   12845   }
   12846   return SQLITE_OK;
   12847 }
   12848 
   12849 /*
   12850 ** Deinitialize the memory allocation subsystem.
   12851 */
   12852 static void sqlite3MemShutdown(void *NotUsed){
   12853   UNUSED_PARAMETER(NotUsed);
   12854   mem.mutex = 0;
   12855 }
   12856 
   12857 /*
   12858 ** Round up a request size to the next valid allocation size.
   12859 */
   12860 static int sqlite3MemRoundup(int n){
   12861   return ROUND8(n);
   12862 }
   12863 
   12864 /*
   12865 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   12866 ** the content of a new memory allocation to unpredictable values and
   12867 ** to clear the content of a freed allocation to unpredictable values.
   12868 */
   12869 static void randomFill(char *pBuf, int nByte){
   12870   unsigned int x, y, r;
   12871   x = SQLITE_PTR_TO_INT(pBuf);
   12872   y = nByte | 1;
   12873   while( nByte >= 4 ){
   12874     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   12875     y = y*1103515245 + 12345;
   12876     r = x ^ y;
   12877     *(int*)pBuf = r;
   12878     pBuf += 4;
   12879     nByte -= 4;
   12880   }
   12881   while( nByte-- > 0 ){
   12882     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   12883     y = y*1103515245 + 12345;
   12884     r = x ^ y;
   12885     *(pBuf++) = r & 0xff;
   12886   }
   12887 }
   12888 
   12889 /*
   12890 ** Allocate nByte bytes of memory.
   12891 */
   12892 static void *sqlite3MemMalloc(int nByte){
   12893   struct MemBlockHdr *pHdr;
   12894   void **pBt;
   12895   char *z;
   12896   int *pInt;
   12897   void *p = 0;
   12898   int totalSize;
   12899   int nReserve;
   12900   sqlite3_mutex_enter(mem.mutex);
   12901   assert( mem.disallow==0 );
   12902   nReserve = ROUND8(nByte);
   12903   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   12904                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   12905   p = malloc(totalSize);
   12906   if( p ){
   12907     z = p;
   12908     pBt = (void**)&z[mem.nTitle];
   12909     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   12910     pHdr->pNext = 0;
   12911     pHdr->pPrev = mem.pLast;
   12912     if( mem.pLast ){
   12913       mem.pLast->pNext = pHdr;
   12914     }else{
   12915       mem.pFirst = pHdr;
   12916     }
   12917     mem.pLast = pHdr;
   12918     pHdr->iForeGuard = FOREGUARD;
   12919     pHdr->nBacktraceSlots = mem.nBacktrace;
   12920     pHdr->nTitle = mem.nTitle;
   12921     if( mem.nBacktrace ){
   12922       void *aAddr[40];
   12923       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   12924       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   12925       assert(pBt[0]);
   12926       if( mem.xBacktrace ){
   12927         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   12928       }
   12929     }else{
   12930       pHdr->nBacktrace = 0;
   12931     }
   12932     if( mem.nTitle ){
   12933       memcpy(z, mem.zTitle, mem.nTitle);
   12934     }
   12935     pHdr->iSize = nByte;
   12936     adjustStats(nByte, +1);
   12937     pInt = (int*)&pHdr[1];
   12938     pInt[nReserve/sizeof(int)] = REARGUARD;
   12939     randomFill((char*)pInt, nByte);
   12940     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   12941     p = (void*)pInt;
   12942   }
   12943   sqlite3_mutex_leave(mem.mutex);
   12944   return p;
   12945 }
   12946 
   12947 /*
   12948 ** Free memory.
   12949 */
   12950 static void sqlite3MemFree(void *pPrior){
   12951   struct MemBlockHdr *pHdr;
   12952   void **pBt;
   12953   char *z;
   12954   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
   12955   pHdr = sqlite3MemsysGetHeader(pPrior);
   12956   pBt = (void**)pHdr;
   12957   pBt -= pHdr->nBacktraceSlots;
   12958   sqlite3_mutex_enter(mem.mutex);
   12959   if( pHdr->pPrev ){
   12960     assert( pHdr->pPrev->pNext==pHdr );
   12961     pHdr->pPrev->pNext = pHdr->pNext;
   12962   }else{
   12963     assert( mem.pFirst==pHdr );
   12964     mem.pFirst = pHdr->pNext;
   12965   }
   12966   if( pHdr->pNext ){
   12967     assert( pHdr->pNext->pPrev==pHdr );
   12968     pHdr->pNext->pPrev = pHdr->pPrev;
   12969   }else{
   12970     assert( mem.pLast==pHdr );
   12971     mem.pLast = pHdr->pPrev;
   12972   }
   12973   z = (char*)pBt;
   12974   z -= pHdr->nTitle;
   12975   adjustStats(pHdr->iSize, -1);
   12976   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   12977                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
   12978   free(z);
   12979   sqlite3_mutex_leave(mem.mutex);
   12980 }
   12981 
   12982 /*
   12983 ** Change the size of an existing memory allocation.
   12984 **
   12985 ** For this debugging implementation, we *always* make a copy of the
   12986 ** allocation into a new place in memory.  In this way, if the
   12987 ** higher level code is using pointer to the old allocation, it is
   12988 ** much more likely to break and we are much more liking to find
   12989 ** the error.
   12990 */
   12991 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   12992   struct MemBlockHdr *pOldHdr;
   12993   void *pNew;
   12994   assert( mem.disallow==0 );
   12995   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   12996   pNew = sqlite3MemMalloc(nByte);
   12997   if( pNew ){
   12998     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
   12999     if( nByte>pOldHdr->iSize ){
   13000       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
   13001     }
   13002     sqlite3MemFree(pPrior);
   13003   }
   13004   return pNew;
   13005 }
   13006 
   13007 /*
   13008 ** Populate the low-level memory allocation function pointers in
   13009 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   13010 */
   13011 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   13012   static const sqlite3_mem_methods defaultMethods = {
   13013      sqlite3MemMalloc,
   13014      sqlite3MemFree,
   13015      sqlite3MemRealloc,
   13016      sqlite3MemSize,
   13017      sqlite3MemRoundup,
   13018      sqlite3MemInit,
   13019      sqlite3MemShutdown,
   13020      0
   13021   };
   13022   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   13023 }
   13024 
   13025 /*
   13026 ** Set the number of backtrace levels kept for each allocation.
   13027 ** A value of zero turns off backtracing.  The number is always rounded
   13028 ** up to a multiple of 2.
   13029 */
   13030 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   13031   if( depth<0 ){ depth = 0; }
   13032   if( depth>20 ){ depth = 20; }
   13033   depth = (depth+1)&0xfe;
   13034   mem.nBacktrace = depth;
   13035 }
   13036 
   13037 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   13038   mem.xBacktrace = xBacktrace;
   13039 }
   13040 
   13041 /*
   13042 ** Set the title string for subsequent allocations.
   13043 */
   13044 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   13045   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   13046   sqlite3_mutex_enter(mem.mutex);
   13047   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   13048   memcpy(mem.zTitle, zTitle, n);
   13049   mem.zTitle[n] = 0;
   13050   mem.nTitle = ROUND8(n);
   13051   sqlite3_mutex_leave(mem.mutex);
   13052 }
   13053 
   13054 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   13055   struct MemBlockHdr *pHdr;
   13056   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   13057     void **pBt = (void**)pHdr;
   13058     pBt -= pHdr->nBacktraceSlots;
   13059     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   13060   }
   13061 }
   13062 
   13063 /*
   13064 ** Open the file indicated and write a log of all unfreed memory
   13065 ** allocations into that log.
   13066 */
   13067 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   13068   FILE *out;
   13069   struct MemBlockHdr *pHdr;
   13070   void **pBt;
   13071   int i;
   13072   out = fopen(zFilename, "w");
   13073   if( out==0 ){
   13074     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   13075                     zFilename);
   13076     return;
   13077   }
   13078   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   13079     char *z = (char*)pHdr;
   13080     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   13081     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   13082             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   13083     if( pHdr->nBacktrace ){
   13084       fflush(out);
   13085       pBt = (void**)pHdr;
   13086       pBt -= pHdr->nBacktraceSlots;
   13087       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   13088       fprintf(out, "\n");
   13089     }
   13090   }
   13091   fprintf(out, "COUNTS:\n");
   13092   for(i=0; i<NCSIZE-1; i++){
   13093     if( mem.nAlloc[i] ){
   13094       fprintf(out, "   %5d: %10d %10d %10d\n",
   13095             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   13096     }
   13097   }
   13098   if( mem.nAlloc[NCSIZE-1] ){
   13099     fprintf(out, "   %5d: %10d %10d %10d\n",
   13100              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   13101              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   13102   }
   13103   fclose(out);
   13104 }
   13105 
   13106 /*
   13107 ** Return the number of times sqlite3MemMalloc() has been called.
   13108 */
   13109 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   13110   int i;
   13111   int nTotal = 0;
   13112   for(i=0; i<NCSIZE; i++){
   13113     nTotal += mem.nAlloc[i];
   13114   }
   13115   return nTotal;
   13116 }
   13117 
   13118 
   13119 #endif /* SQLITE_MEMDEBUG */
   13120 
   13121 /************** End of mem2.c ************************************************/
   13122 /************** Begin file mem3.c ********************************************/
   13123 /*
   13124 ** 2007 October 14
   13125 **
   13126 ** The author disclaims copyright to this source code.  In place of
   13127 ** a legal notice, here is a blessing:
   13128 **
   13129 **    May you do good and not evil.
   13130 **    May you find forgiveness for yourself and forgive others.
   13131 **    May you share freely, never taking more than you give.
   13132 **
   13133 *************************************************************************
   13134 ** This file contains the C functions that implement a memory
   13135 ** allocation subsystem for use by SQLite.
   13136 **
   13137 ** This version of the memory allocation subsystem omits all
   13138 ** use of malloc(). The SQLite user supplies a block of memory
   13139 ** before calling sqlite3_initialize() from which allocations
   13140 ** are made and returned by the xMalloc() and xRealloc()
   13141 ** implementations. Once sqlite3_initialize() has been called,
   13142 ** the amount of memory available to SQLite is fixed and cannot
   13143 ** be changed.
   13144 **
   13145 ** This version of the memory allocation subsystem is included
   13146 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   13147 */
   13148 
   13149 /*
   13150 ** This version of the memory allocator is only built into the library
   13151 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   13152 ** mean that the library will use a memory-pool by default, just that
   13153 ** it is available. The mempool allocator is activated by calling
   13154 ** sqlite3_config().
   13155 */
   13156 #ifdef SQLITE_ENABLE_MEMSYS3
   13157 
   13158 /*
   13159 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   13160 */
   13161 #define MX_SMALL 10
   13162 
   13163 
   13164 /*
   13165 ** Number of freelist hash slots
   13166 */
   13167 #define N_HASH  61
   13168 
   13169 /*
   13170 ** A memory allocation (also called a "chunk") consists of two or
   13171 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   13172 ** a header that is not returned to the user.
   13173 **
   13174 ** A chunk is two or more blocks that is either checked out or
   13175 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   13176 ** size of the allocation in blocks if the allocation is free.
   13177 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   13178 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   13179 ** is true if the previous chunk is checked out and false if the
   13180 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   13181 ** the previous chunk in blocks if the previous chunk is on the
   13182 ** freelist. If the previous chunk is checked out, then
   13183 ** u.hdr.prevSize can be part of the data for that chunk and should
   13184 ** not be read or written.
   13185 **
   13186 ** We often identify a chunk by its index in mem3.aPool[].  When
   13187 ** this is done, the chunk index refers to the second block of
   13188 ** the chunk.  In this way, the first chunk has an index of 1.
   13189 ** A chunk index of 0 means "no such chunk" and is the equivalent
   13190 ** of a NULL pointer.
   13191 **
   13192 ** The second block of free chunks is of the form u.list.  The
   13193 ** two fields form a double-linked list of chunks of related sizes.
   13194 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   13195 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   13196 **
   13197 ** The second block of a chunk is user data if the chunk is checked
   13198 ** out.  If a chunk is checked out, the user data may extend into
   13199 ** the u.hdr.prevSize value of the following chunk.
   13200 */
   13201 typedef struct Mem3Block Mem3Block;
   13202 struct Mem3Block {
   13203   union {
   13204     struct {
   13205       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   13206       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   13207     } hdr;
   13208     struct {
   13209       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   13210       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   13211     } list;
   13212   } u;
   13213 };
   13214 
   13215 /*
   13216 ** All of the static variables used by this module are collected
   13217 ** into a single structure named "mem3".  This is to keep the
   13218 ** static variables organized and to reduce namespace pollution
   13219 ** when this module is combined with other in the amalgamation.
   13220 */
   13221 static SQLITE_WSD struct Mem3Global {
   13222   /*
   13223   ** Memory available for allocation. nPool is the size of the array
   13224   ** (in Mem3Blocks) pointed to by aPool less 2.
   13225   */
   13226   u32 nPool;
   13227   Mem3Block *aPool;
   13228 
   13229   /*
   13230   ** True if we are evaluating an out-of-memory callback.
   13231   */
   13232   int alarmBusy;
   13233 
   13234   /*
   13235   ** Mutex to control access to the memory allocation subsystem.
   13236   */
   13237   sqlite3_mutex *mutex;
   13238 
   13239   /*
   13240   ** The minimum amount of free space that we have seen.
   13241   */
   13242   u32 mnMaster;
   13243 
   13244   /*
   13245   ** iMaster is the index of the master chunk.  Most new allocations
   13246   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   13247   ** of the current master.  iMaster is 0 if there is not master chunk.
   13248   ** The master chunk is not in either the aiHash[] or aiSmall[].
   13249   */
   13250   u32 iMaster;
   13251   u32 szMaster;
   13252 
   13253   /*
   13254   ** Array of lists of free blocks according to the block size
   13255   ** for smaller chunks, or a hash on the block size for larger
   13256   ** chunks.
   13257   */
   13258   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   13259   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   13260 } mem3 = { 97535575 };
   13261 
   13262 #define mem3 GLOBAL(struct Mem3Global, mem3)
   13263 
   13264 /*
   13265 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   13266 ** on.  *pRoot is the list that i is a member of.
   13267 */
   13268 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   13269   u32 next = mem3.aPool[i].u.list.next;
   13270   u32 prev = mem3.aPool[i].u.list.prev;
   13271   assert( sqlite3_mutex_held(mem3.mutex) );
   13272   if( prev==0 ){
   13273     *pRoot = next;
   13274   }else{
   13275     mem3.aPool[prev].u.list.next = next;
   13276   }
   13277   if( next ){
   13278     mem3.aPool[next].u.list.prev = prev;
   13279   }
   13280   mem3.aPool[i].u.list.next = 0;
   13281   mem3.aPool[i].u.list.prev = 0;
   13282 }
   13283 
   13284 /*
   13285 ** Unlink the chunk at index i from
   13286 ** whatever list is currently a member of.
   13287 */
   13288 static void memsys3Unlink(u32 i){
   13289   u32 size, hash;
   13290   assert( sqlite3_mutex_held(mem3.mutex) );
   13291   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   13292   assert( i>=1 );
   13293   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13294   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   13295   assert( size>=2 );
   13296   if( size <= MX_SMALL ){
   13297     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   13298   }else{
   13299     hash = size % N_HASH;
   13300     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   13301   }
   13302 }
   13303 
   13304 /*
   13305 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   13306 ** at *pRoot.
   13307 */
   13308 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   13309   assert( sqlite3_mutex_held(mem3.mutex) );
   13310   mem3.aPool[i].u.list.next = *pRoot;
   13311   mem3.aPool[i].u.list.prev = 0;
   13312   if( *pRoot ){
   13313     mem3.aPool[*pRoot].u.list.prev = i;
   13314   }
   13315   *pRoot = i;
   13316 }
   13317 
   13318 /*
   13319 ** Link the chunk at index i into either the appropriate
   13320 ** small chunk list, or into the large chunk hash table.
   13321 */
   13322 static void memsys3Link(u32 i){
   13323   u32 size, hash;
   13324   assert( sqlite3_mutex_held(mem3.mutex) );
   13325   assert( i>=1 );
   13326   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   13327   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13328   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   13329   assert( size>=2 );
   13330   if( size <= MX_SMALL ){
   13331     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   13332   }else{
   13333     hash = size % N_HASH;
   13334     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   13335   }
   13336 }
   13337 
   13338 /*
   13339 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   13340 ** will already be held (obtained by code in malloc.c) if
   13341 ** sqlite3GlobalConfig.bMemStat is true.
   13342 */
   13343 static void memsys3Enter(void){
   13344   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   13345     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   13346   }
   13347   sqlite3_mutex_enter(mem3.mutex);
   13348 }
   13349 static void memsys3Leave(void){
   13350   sqlite3_mutex_leave(mem3.mutex);
   13351 }
   13352 
   13353 /*
   13354 ** Called when we are unable to satisfy an allocation of nBytes.
   13355 */
   13356 static void memsys3OutOfMemory(int nByte){
   13357   if( !mem3.alarmBusy ){
   13358     mem3.alarmBusy = 1;
   13359     assert( sqlite3_mutex_held(mem3.mutex) );
   13360     sqlite3_mutex_leave(mem3.mutex);
   13361     sqlite3_release_memory(nByte);
   13362     sqlite3_mutex_enter(mem3.mutex);
   13363     mem3.alarmBusy = 0;
   13364   }
   13365 }
   13366 
   13367 
   13368 /*
   13369 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   13370 ** size parameters for check-out and return a pointer to the
   13371 ** user portion of the chunk.
   13372 */
   13373 static void *memsys3Checkout(u32 i, u32 nBlock){
   13374   u32 x;
   13375   assert( sqlite3_mutex_held(mem3.mutex) );
   13376   assert( i>=1 );
   13377   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   13378   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   13379   x = mem3.aPool[i-1].u.hdr.size4x;
   13380   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   13381   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   13382   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   13383   return &mem3.aPool[i];
   13384 }
   13385 
   13386 /*
   13387 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   13388 ** Return a pointer to the new allocation.  Or, if the master chunk
   13389 ** is not large enough, return 0.
   13390 */
   13391 static void *memsys3FromMaster(u32 nBlock){
   13392   assert( sqlite3_mutex_held(mem3.mutex) );
   13393   assert( mem3.szMaster>=nBlock );
   13394   if( nBlock>=mem3.szMaster-1 ){
   13395     /* Use the entire master */
   13396     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   13397     mem3.iMaster = 0;
   13398     mem3.szMaster = 0;
   13399     mem3.mnMaster = 0;
   13400     return p;
   13401   }else{
   13402     /* Split the master block.  Return the tail. */
   13403     u32 newi, x;
   13404     newi = mem3.iMaster + mem3.szMaster - nBlock;
   13405     assert( newi > mem3.iMaster+1 );
   13406     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   13407     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   13408     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   13409     mem3.szMaster -= nBlock;
   13410     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   13411     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13412     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13413     if( mem3.szMaster < mem3.mnMaster ){
   13414       mem3.mnMaster = mem3.szMaster;
   13415     }
   13416     return (void*)&mem3.aPool[newi];
   13417   }
   13418 }
   13419 
   13420 /*
   13421 ** *pRoot is the head of a list of free chunks of the same size
   13422 ** or same size hash.  In other words, *pRoot is an entry in either
   13423 ** mem3.aiSmall[] or mem3.aiHash[].
   13424 **
   13425 ** This routine examines all entries on the given list and tries
   13426 ** to coalesce each entries with adjacent free chunks.
   13427 **
   13428 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   13429 ** the current mem3.iMaster with the new larger chunk.  In order for
   13430 ** this mem3.iMaster replacement to work, the master chunk must be
   13431 ** linked into the hash tables.  That is not the normal state of
   13432 ** affairs, of course.  The calling routine must link the master
   13433 ** chunk before invoking this routine, then must unlink the (possibly
   13434 ** changed) master chunk once this routine has finished.
   13435 */
   13436 static void memsys3Merge(u32 *pRoot){
   13437   u32 iNext, prev, size, i, x;
   13438 
   13439   assert( sqlite3_mutex_held(mem3.mutex) );
   13440   for(i=*pRoot; i>0; i=iNext){
   13441     iNext = mem3.aPool[i].u.list.next;
   13442     size = mem3.aPool[i-1].u.hdr.size4x;
   13443     assert( (size&1)==0 );
   13444     if( (size&2)==0 ){
   13445       memsys3UnlinkFromList(i, pRoot);
   13446       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   13447       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   13448       if( prev==iNext ){
   13449         iNext = mem3.aPool[prev].u.list.next;
   13450       }
   13451       memsys3Unlink(prev);
   13452       size = i + size/4 - prev;
   13453       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   13454       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   13455       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   13456       memsys3Link(prev);
   13457       i = prev;
   13458     }else{
   13459       size /= 4;
   13460     }
   13461     if( size>mem3.szMaster ){
   13462       mem3.iMaster = i;
   13463       mem3.szMaster = size;
   13464     }
   13465   }
   13466 }
   13467 
   13468 /*
   13469 ** Return a block of memory of at least nBytes in size.
   13470 ** Return NULL if unable.
   13471 **
   13472 ** This function assumes that the necessary mutexes, if any, are
   13473 ** already held by the caller. Hence "Unsafe".
   13474 */
   13475 static void *memsys3MallocUnsafe(int nByte){
   13476   u32 i;
   13477   u32 nBlock;
   13478   u32 toFree;
   13479 
   13480   assert( sqlite3_mutex_held(mem3.mutex) );
   13481   assert( sizeof(Mem3Block)==8 );
   13482   if( nByte<=12 ){
   13483     nBlock = 2;
   13484   }else{
   13485     nBlock = (nByte + 11)/8;
   13486   }
   13487   assert( nBlock>=2 );
   13488 
   13489   /* STEP 1:
   13490   ** Look for an entry of the correct size in either the small
   13491   ** chunk table or in the large chunk hash table.  This is
   13492   ** successful most of the time (about 9 times out of 10).
   13493   */
   13494   if( nBlock <= MX_SMALL ){
   13495     i = mem3.aiSmall[nBlock-2];
   13496     if( i>0 ){
   13497       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   13498       return memsys3Checkout(i, nBlock);
   13499     }
   13500   }else{
   13501     int hash = nBlock % N_HASH;
   13502     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   13503       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   13504         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   13505         return memsys3Checkout(i, nBlock);
   13506       }
   13507     }
   13508   }
   13509 
   13510   /* STEP 2:
   13511   ** Try to satisfy the allocation by carving a piece off of the end
   13512   ** of the master chunk.  This step usually works if step 1 fails.
   13513   */
   13514   if( mem3.szMaster>=nBlock ){
   13515     return memsys3FromMaster(nBlock);
   13516   }
   13517 
   13518 
   13519   /* STEP 3:
   13520   ** Loop through the entire memory pool.  Coalesce adjacent free
   13521   ** chunks.  Recompute the master chunk as the largest free chunk.
   13522   ** Then try again to satisfy the allocation by carving a piece off
   13523   ** of the end of the master chunk.  This step happens very
   13524   ** rarely (we hope!)
   13525   */
   13526   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   13527     memsys3OutOfMemory(toFree);
   13528     if( mem3.iMaster ){
   13529       memsys3Link(mem3.iMaster);
   13530       mem3.iMaster = 0;
   13531       mem3.szMaster = 0;
   13532     }
   13533     for(i=0; i<N_HASH; i++){
   13534       memsys3Merge(&mem3.aiHash[i]);
   13535     }
   13536     for(i=0; i<MX_SMALL-1; i++){
   13537       memsys3Merge(&mem3.aiSmall[i]);
   13538     }
   13539     if( mem3.szMaster ){
   13540       memsys3Unlink(mem3.iMaster);
   13541       if( mem3.szMaster>=nBlock ){
   13542         return memsys3FromMaster(nBlock);
   13543       }
   13544     }
   13545   }
   13546 
   13547   /* If none of the above worked, then we fail. */
   13548   return 0;
   13549 }
   13550 
   13551 /*
   13552 ** Free an outstanding memory allocation.
   13553 **
   13554 ** This function assumes that the necessary mutexes, if any, are
   13555 ** already held by the caller. Hence "Unsafe".
   13556 */
   13557 void memsys3FreeUnsafe(void *pOld){
   13558   Mem3Block *p = (Mem3Block*)pOld;
   13559   int i;
   13560   u32 size, x;
   13561   assert( sqlite3_mutex_held(mem3.mutex) );
   13562   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   13563   i = p - mem3.aPool;
   13564   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   13565   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13566   assert( i+size<=mem3.nPool+1 );
   13567   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   13568   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   13569   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   13570   memsys3Link(i);
   13571 
   13572   /* Try to expand the master using the newly freed chunk */
   13573   if( mem3.iMaster ){
   13574     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   13575       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   13576       mem3.iMaster -= size;
   13577       mem3.szMaster += size;
   13578       memsys3Unlink(mem3.iMaster);
   13579       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13580       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13581       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   13582     }
   13583     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13584     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   13585       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   13586       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   13587       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13588       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   13589     }
   13590   }
   13591 }
   13592 
   13593 /*
   13594 ** Return the size of an outstanding allocation, in bytes.  The
   13595 ** size returned omits the 8-byte header overhead.  This only
   13596 ** works for chunks that are currently checked out.
   13597 */
   13598 static int memsys3Size(void *p){
   13599   Mem3Block *pBlock;
   13600   if( p==0 ) return 0;
   13601   pBlock = (Mem3Block*)p;
   13602   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   13603   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   13604 }
   13605 
   13606 /*
   13607 ** Round up a request size to the next valid allocation size.
   13608 */
   13609 static int memsys3Roundup(int n){
   13610   if( n<=12 ){
   13611     return 12;
   13612   }else{
   13613     return ((n+11)&~7) - 4;
   13614   }
   13615 }
   13616 
   13617 /*
   13618 ** Allocate nBytes of memory.
   13619 */
   13620 static void *memsys3Malloc(int nBytes){
   13621   sqlite3_int64 *p;
   13622   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   13623   memsys3Enter();
   13624   p = memsys3MallocUnsafe(nBytes);
   13625   memsys3Leave();
   13626   return (void*)p;
   13627 }
   13628 
   13629 /*
   13630 ** Free memory.
   13631 */
   13632 void memsys3Free(void *pPrior){
   13633   assert( pPrior );
   13634   memsys3Enter();
   13635   memsys3FreeUnsafe(pPrior);
   13636   memsys3Leave();
   13637 }
   13638 
   13639 /*
   13640 ** Change the size of an existing memory allocation
   13641 */
   13642 void *memsys3Realloc(void *pPrior, int nBytes){
   13643   int nOld;
   13644   void *p;
   13645   if( pPrior==0 ){
   13646     return sqlite3_malloc(nBytes);
   13647   }
   13648   if( nBytes<=0 ){
   13649     sqlite3_free(pPrior);
   13650     return 0;
   13651   }
   13652   nOld = memsys3Size(pPrior);
   13653   if( nBytes<=nOld && nBytes>=nOld-128 ){
   13654     return pPrior;
   13655   }
   13656   memsys3Enter();
   13657   p = memsys3MallocUnsafe(nBytes);
   13658   if( p ){
   13659     if( nOld<nBytes ){
   13660       memcpy(p, pPrior, nOld);
   13661     }else{
   13662       memcpy(p, pPrior, nBytes);
   13663     }
   13664     memsys3FreeUnsafe(pPrior);
   13665   }
   13666   memsys3Leave();
   13667   return p;
   13668 }
   13669 
   13670 /*
   13671 ** Initialize this module.
   13672 */
   13673 static int memsys3Init(void *NotUsed){
   13674   UNUSED_PARAMETER(NotUsed);
   13675   if( !sqlite3GlobalConfig.pHeap ){
   13676     return SQLITE_ERROR;
   13677   }
   13678 
   13679   /* Store a pointer to the memory block in global structure mem3. */
   13680   assert( sizeof(Mem3Block)==8 );
   13681   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   13682   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   13683 
   13684   /* Initialize the master block. */
   13685   mem3.szMaster = mem3.nPool;
   13686   mem3.mnMaster = mem3.szMaster;
   13687   mem3.iMaster = 1;
   13688   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   13689   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   13690   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   13691 
   13692   return SQLITE_OK;
   13693 }
   13694 
   13695 /*
   13696 ** Deinitialize this module.
   13697 */
   13698 static void memsys3Shutdown(void *NotUsed){
   13699   UNUSED_PARAMETER(NotUsed);
   13700   mem3.mutex = 0;
   13701   return;
   13702 }
   13703 
   13704 
   13705 
   13706 /*
   13707 ** Open the file indicated and write a log of all unfreed memory
   13708 ** allocations into that log.
   13709 */
   13710 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   13711 #ifdef SQLITE_DEBUG
   13712   FILE *out;
   13713   u32 i, j;
   13714   u32 size;
   13715   if( zFilename==0 || zFilename[0]==0 ){
   13716     out = stdout;
   13717   }else{
   13718     out = fopen(zFilename, "w");
   13719     if( out==0 ){
   13720       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   13721                       zFilename);
   13722       return;
   13723     }
   13724   }
   13725   memsys3Enter();
   13726   fprintf(out, "CHUNKS:\n");
   13727   for(i=1; i<=mem3.nPool; i+=size/4){
   13728     size = mem3.aPool[i-1].u.hdr.size4x;
   13729     if( size/4<=1 ){
   13730       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   13731       assert( 0 );
   13732       break;
   13733     }
   13734     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   13735       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   13736       assert( 0 );
   13737       break;
   13738     }
   13739     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   13740       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   13741       assert( 0 );
   13742       break;
   13743     }
   13744     if( size&1 ){
   13745       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   13746     }else{
   13747       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   13748                   i==mem3.iMaster ? " **master**" : "");
   13749     }
   13750   }
   13751   for(i=0; i<MX_SMALL-1; i++){
   13752     if( mem3.aiSmall[i]==0 ) continue;
   13753     fprintf(out, "small(%2d):", i);
   13754     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   13755       fprintf(out, " %p(%d)", &mem3.aPool[j],
   13756               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   13757     }
   13758     fprintf(out, "\n");
   13759   }
   13760   for(i=0; i<N_HASH; i++){
   13761     if( mem3.aiHash[i]==0 ) continue;
   13762     fprintf(out, "hash(%2d):", i);
   13763     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   13764       fprintf(out, " %p(%d)", &mem3.aPool[j],
   13765               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   13766     }
   13767     fprintf(out, "\n");
   13768   }
   13769   fprintf(out, "master=%d\n", mem3.iMaster);
   13770   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   13771   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   13772   sqlite3_mutex_leave(mem3.mutex);
   13773   if( out==stdout ){
   13774     fflush(stdout);
   13775   }else{
   13776     fclose(out);
   13777   }
   13778 #else
   13779   UNUSED_PARAMETER(zFilename);
   13780 #endif
   13781 }
   13782 
   13783 /*
   13784 ** This routine is the only routine in this file with external
   13785 ** linkage.
   13786 **
   13787 ** Populate the low-level memory allocation function pointers in
   13788 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   13789 ** arguments specify the block of memory to manage.
   13790 **
   13791 ** This routine is only called by sqlite3_config(), and therefore
   13792 ** is not required to be threadsafe (it is not).
   13793 */
   13794 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   13795   static const sqlite3_mem_methods mempoolMethods = {
   13796      memsys3Malloc,
   13797      memsys3Free,
   13798      memsys3Realloc,
   13799      memsys3Size,
   13800      memsys3Roundup,
   13801      memsys3Init,
   13802      memsys3Shutdown,
   13803      0
   13804   };
   13805   return &mempoolMethods;
   13806 }
   13807 
   13808 #endif /* SQLITE_ENABLE_MEMSYS3 */
   13809 
   13810 /************** End of mem3.c ************************************************/
   13811 /************** Begin file mem5.c ********************************************/
   13812 /*
   13813 ** 2007 October 14
   13814 **
   13815 ** The author disclaims copyright to this source code.  In place of
   13816 ** a legal notice, here is a blessing:
   13817 **
   13818 **    May you do good and not evil.
   13819 **    May you find forgiveness for yourself and forgive others.
   13820 **    May you share freely, never taking more than you give.
   13821 **
   13822 *************************************************************************
   13823 ** This file contains the C functions that implement a memory
   13824 ** allocation subsystem for use by SQLite.
   13825 **
   13826 ** This version of the memory allocation subsystem omits all
   13827 ** use of malloc(). The application gives SQLite a block of memory
   13828 ** before calling sqlite3_initialize() from which allocations
   13829 ** are made and returned by the xMalloc() and xRealloc()
   13830 ** implementations. Once sqlite3_initialize() has been called,
   13831 ** the amount of memory available to SQLite is fixed and cannot
   13832 ** be changed.
   13833 **
   13834 ** This version of the memory allocation subsystem is included
   13835 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   13836 **
   13837 ** This memory allocator uses the following algorithm:
   13838 **
   13839 **   1.  All memory allocations sizes are rounded up to a power of 2.
   13840 **
   13841 **   2.  If two adjacent free blocks are the halves of a larger block,
   13842 **       then the two blocks are coalesed into the single larger block.
   13843 **
   13844 **   3.  New memory is allocated from the first available free block.
   13845 **
   13846 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   13847 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   13848 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   13849 **
   13850 ** Let n be the size of the largest allocation divided by the minimum
   13851 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   13852 ** be the maximum amount of memory ever outstanding at one time.  Let
   13853 ** N be the total amount of memory available for allocation.  Robson
   13854 ** proved that this memory allocator will never breakdown due to
   13855 ** fragmentation as long as the following constraint holds:
   13856 **
   13857 **      N >=  M*(1 + log2(n)/2) - n + 1
   13858 **
   13859 ** The sqlite3_status() logic tracks the maximum values of n and M so
   13860 ** that an application can, at any time, verify this constraint.
   13861 */
   13862 
   13863 /*
   13864 ** This version of the memory allocator is used only when
   13865 ** SQLITE_ENABLE_MEMSYS5 is defined.
   13866 */
   13867 #ifdef SQLITE_ENABLE_MEMSYS5
   13868 
   13869 /*
   13870 ** A minimum allocation is an instance of the following structure.
   13871 ** Larger allocations are an array of these structures where the
   13872 ** size of the array is a power of 2.
   13873 **
   13874 ** The size of this object must be a power of two.  That fact is
   13875 ** verified in memsys5Init().
   13876 */
   13877 typedef struct Mem5Link Mem5Link;
   13878 struct Mem5Link {
   13879   int next;       /* Index of next free chunk */
   13880   int prev;       /* Index of previous free chunk */
   13881 };
   13882 
   13883 /*
   13884 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   13885 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   13886 ** it is not actually possible to reach this limit.
   13887 */
   13888 #define LOGMAX 30
   13889 
   13890 /*
   13891 ** Masks used for mem5.aCtrl[] elements.
   13892 */
   13893 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   13894 #define CTRL_FREE     0x20    /* True if not checked out */
   13895 
   13896 /*
   13897 ** All of the static variables used by this module are collected
   13898 ** into a single structure named "mem5".  This is to keep the
   13899 ** static variables organized and to reduce namespace pollution
   13900 ** when this module is combined with other in the amalgamation.
   13901 */
   13902 static SQLITE_WSD struct Mem5Global {
   13903   /*
   13904   ** Memory available for allocation
   13905   */
   13906   int szAtom;      /* Smallest possible allocation in bytes */
   13907   int nBlock;      /* Number of szAtom sized blocks in zPool */
   13908   u8 *zPool;       /* Memory available to be allocated */
   13909 
   13910   /*
   13911   ** Mutex to control access to the memory allocation subsystem.
   13912   */
   13913   sqlite3_mutex *mutex;
   13914 
   13915   /*
   13916   ** Performance statistics
   13917   */
   13918   u64 nAlloc;         /* Total number of calls to malloc */
   13919   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   13920   u64 totalExcess;    /* Total internal fragmentation */
   13921   u32 currentOut;     /* Current checkout, including internal fragmentation */
   13922   u32 currentCount;   /* Current number of distinct checkouts */
   13923   u32 maxOut;         /* Maximum instantaneous currentOut */
   13924   u32 maxCount;       /* Maximum instantaneous currentCount */
   13925   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   13926 
   13927   /*
   13928   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   13929   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   13930   ** and so forth.
   13931   */
   13932   int aiFreelist[LOGMAX+1];
   13933 
   13934   /*
   13935   ** Space for tracking which blocks are checked out and the size
   13936   ** of each block.  One byte per block.
   13937   */
   13938   u8 *aCtrl;
   13939 
   13940 } mem5 = { 0 };
   13941 
   13942 /*
   13943 ** Access the static variable through a macro for SQLITE_OMIT_WSD
   13944 */
   13945 #define mem5 GLOBAL(struct Mem5Global, mem5)
   13946 
   13947 /*
   13948 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   13949 ** structures, return a pointer to the idx-th such lik.
   13950 */
   13951 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   13952 
   13953 /*
   13954 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   13955 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   13956 */
   13957 static void memsys5Unlink(int i, int iLogsize){
   13958   int next, prev;
   13959   assert( i>=0 && i<mem5.nBlock );
   13960   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   13961   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   13962 
   13963   next = MEM5LINK(i)->next;
   13964   prev = MEM5LINK(i)->prev;
   13965   if( prev<0 ){
   13966     mem5.aiFreelist[iLogsize] = next;
   13967   }else{
   13968     MEM5LINK(prev)->next = next;
   13969   }
   13970   if( next>=0 ){
   13971     MEM5LINK(next)->prev = prev;
   13972   }
   13973 }
   13974 
   13975 /*
   13976 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   13977 ** free list.
   13978 */
   13979 static void memsys5Link(int i, int iLogsize){
   13980   int x;
   13981   assert( sqlite3_mutex_held(mem5.mutex) );
   13982   assert( i>=0 && i<mem5.nBlock );
   13983   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   13984   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   13985 
   13986   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   13987   MEM5LINK(i)->prev = -1;
   13988   if( x>=0 ){
   13989     assert( x<mem5.nBlock );
   13990     MEM5LINK(x)->prev = i;
   13991   }
   13992   mem5.aiFreelist[iLogsize] = i;
   13993 }
   13994 
   13995 /*
   13996 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   13997 ** will already be held (obtained by code in malloc.c) if
   13998 ** sqlite3GlobalConfig.bMemStat is true.
   13999 */
   14000 static void memsys5Enter(void){
   14001   sqlite3_mutex_enter(mem5.mutex);
   14002 }
   14003 static void memsys5Leave(void){
   14004   sqlite3_mutex_leave(mem5.mutex);
   14005 }
   14006 
   14007 /*
   14008 ** Return the size of an outstanding allocation, in bytes.  The
   14009 ** size returned omits the 8-byte header overhead.  This only
   14010 ** works for chunks that are currently checked out.
   14011 */
   14012 static int memsys5Size(void *p){
   14013   int iSize = 0;
   14014   if( p ){
   14015     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
   14016     assert( i>=0 && i<mem5.nBlock );
   14017     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   14018   }
   14019   return iSize;
   14020 }
   14021 
   14022 /*
   14023 ** Find the first entry on the freelist iLogsize.  Unlink that
   14024 ** entry and return its index.
   14025 */
   14026 static int memsys5UnlinkFirst(int iLogsize){
   14027   int i;
   14028   int iFirst;
   14029 
   14030   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   14031   i = iFirst = mem5.aiFreelist[iLogsize];
   14032   assert( iFirst>=0 );
   14033   while( i>0 ){
   14034     if( i<iFirst ) iFirst = i;
   14035     i = MEM5LINK(i)->next;
   14036   }
   14037   memsys5Unlink(iFirst, iLogsize);
   14038   return iFirst;
   14039 }
   14040 
   14041 /*
   14042 ** Return a block of memory of at least nBytes in size.
   14043 ** Return NULL if unable.  Return NULL if nBytes==0.
   14044 **
   14045 ** The caller guarantees that nByte positive.
   14046 **
   14047 ** The caller has obtained a mutex prior to invoking this
   14048 ** routine so there is never any chance that two or more
   14049 ** threads can be in this routine at the same time.
   14050 */
   14051 static void *memsys5MallocUnsafe(int nByte){
   14052   int i;           /* Index of a mem5.aPool[] slot */
   14053   int iBin;        /* Index into mem5.aiFreelist[] */
   14054   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   14055   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   14056 
   14057   /* nByte must be a positive */
   14058   assert( nByte>0 );
   14059 
   14060   /* Keep track of the maximum allocation request.  Even unfulfilled
   14061   ** requests are counted */
   14062   if( (u32)nByte>mem5.maxRequest ){
   14063     mem5.maxRequest = nByte;
   14064   }
   14065 
   14066   /* Abort if the requested allocation size is larger than the largest
   14067   ** power of two that we can represent using 32-bit signed integers.
   14068   */
   14069   if( nByte > 0x40000000 ){
   14070     return 0;
   14071   }
   14072 
   14073   /* Round nByte up to the next valid power of two */
   14074   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
   14075 
   14076   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   14077   ** block.  If not, then split a block of the next larger power of
   14078   ** two in order to create a new free block of size iLogsize.
   14079   */
   14080   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
   14081   if( iBin>LOGMAX ){
   14082     testcase( sqlite3GlobalConfig.xLog!=0 );
   14083     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   14084     return 0;
   14085   }
   14086   i = memsys5UnlinkFirst(iBin);
   14087   while( iBin>iLogsize ){
   14088     int newSize;
   14089 
   14090     iBin--;
   14091     newSize = 1 << iBin;
   14092     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   14093     memsys5Link(i+newSize, iBin);
   14094   }
   14095   mem5.aCtrl[i] = iLogsize;
   14096 
   14097   /* Update allocator performance statistics. */
   14098   mem5.nAlloc++;
   14099   mem5.totalAlloc += iFullSz;
   14100   mem5.totalExcess += iFullSz - nByte;
   14101   mem5.currentCount++;
   14102   mem5.currentOut += iFullSz;
   14103   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   14104   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   14105 
   14106   /* Return a pointer to the allocated memory. */
   14107   return (void*)&mem5.zPool[i*mem5.szAtom];
   14108 }
   14109 
   14110 /*
   14111 ** Free an outstanding memory allocation.
   14112 */
   14113 static void memsys5FreeUnsafe(void *pOld){
   14114   u32 size, iLogsize;
   14115   int iBlock;
   14116 
   14117   /* Set iBlock to the index of the block pointed to by pOld in
   14118   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   14119   */
   14120   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
   14121 
   14122   /* Check that the pointer pOld points to a valid, non-free block. */
   14123   assert( iBlock>=0 && iBlock<mem5.nBlock );
   14124   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   14125   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   14126 
   14127   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   14128   size = 1<<iLogsize;
   14129   assert( iBlock+size-1<(u32)mem5.nBlock );
   14130 
   14131   mem5.aCtrl[iBlock] |= CTRL_FREE;
   14132   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   14133   assert( mem5.currentCount>0 );
   14134   assert( mem5.currentOut>=(size*mem5.szAtom) );
   14135   mem5.currentCount--;
   14136   mem5.currentOut -= size*mem5.szAtom;
   14137   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   14138   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   14139 
   14140   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   14141   while( ALWAYS(iLogsize<LOGMAX) ){
   14142     int iBuddy;
   14143     if( (iBlock>>iLogsize) & 1 ){
   14144       iBuddy = iBlock - size;
   14145     }else{
   14146       iBuddy = iBlock + size;
   14147     }
   14148     assert( iBuddy>=0 );
   14149     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
   14150     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   14151     memsys5Unlink(iBuddy, iLogsize);
   14152     iLogsize++;
   14153     if( iBuddy<iBlock ){
   14154       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   14155       mem5.aCtrl[iBlock] = 0;
   14156       iBlock = iBuddy;
   14157     }else{
   14158       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   14159       mem5.aCtrl[iBuddy] = 0;
   14160     }
   14161     size *= 2;
   14162   }
   14163   memsys5Link(iBlock, iLogsize);
   14164 }
   14165 
   14166 /*
   14167 ** Allocate nBytes of memory
   14168 */
   14169 static void *memsys5Malloc(int nBytes){
   14170   sqlite3_int64 *p = 0;
   14171   if( nBytes>0 ){
   14172     memsys5Enter();
   14173     p = memsys5MallocUnsafe(nBytes);
   14174     memsys5Leave();
   14175   }
   14176   return (void*)p;
   14177 }
   14178 
   14179 /*
   14180 ** Free memory.
   14181 **
   14182 ** The outer layer memory allocator prevents this routine from
   14183 ** being called with pPrior==0.
   14184 */
   14185 static void memsys5Free(void *pPrior){
   14186   assert( pPrior!=0 );
   14187   memsys5Enter();
   14188   memsys5FreeUnsafe(pPrior);
   14189   memsys5Leave();
   14190 }
   14191 
   14192 /*
   14193 ** Change the size of an existing memory allocation.
   14194 **
   14195 ** The outer layer memory allocator prevents this routine from
   14196 ** being called with pPrior==0.
   14197 **
   14198 ** nBytes is always a value obtained from a prior call to
   14199 ** memsys5Round().  Hence nBytes is always a non-negative power
   14200 ** of two.  If nBytes==0 that means that an oversize allocation
   14201 ** (an allocation larger than 0x40000000) was requested and this
   14202 ** routine should return 0 without freeing pPrior.
   14203 */
   14204 static void *memsys5Realloc(void *pPrior, int nBytes){
   14205   int nOld;
   14206   void *p;
   14207   assert( pPrior!=0 );
   14208   assert( (nBytes&(nBytes-1))==0 );
   14209   assert( nBytes>=0 );
   14210   if( nBytes==0 ){
   14211     return 0;
   14212   }
   14213   nOld = memsys5Size(pPrior);
   14214   if( nBytes<=nOld ){
   14215     return pPrior;
   14216   }
   14217   memsys5Enter();
   14218   p = memsys5MallocUnsafe(nBytes);
   14219   if( p ){
   14220     memcpy(p, pPrior, nOld);
   14221     memsys5FreeUnsafe(pPrior);
   14222   }
   14223   memsys5Leave();
   14224   return p;
   14225 }
   14226 
   14227 /*
   14228 ** Round up a request size to the next valid allocation size.  If
   14229 ** the allocation is too large to be handled by this allocation system,
   14230 ** return 0.
   14231 **
   14232 ** All allocations must be a power of two and must be expressed by a
   14233 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   14234 ** or 1073741824 bytes.
   14235 */
   14236 static int memsys5Roundup(int n){
   14237   int iFullSz;
   14238   if( n > 0x40000000 ) return 0;
   14239   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   14240   return iFullSz;
   14241 }
   14242 
   14243 /*
   14244 ** Return the ceiling of the logarithm base 2 of iValue.
   14245 **
   14246 ** Examples:   memsys5Log(1) -> 0
   14247 **             memsys5Log(2) -> 1
   14248 **             memsys5Log(4) -> 2
   14249 **             memsys5Log(5) -> 3
   14250 **             memsys5Log(8) -> 3
   14251 **             memsys5Log(9) -> 4
   14252 */
   14253 static int memsys5Log(int iValue){
   14254   int iLog;
   14255   for(iLog=0; (1<<iLog)<iValue; iLog++);
   14256   return iLog;
   14257 }
   14258 
   14259 /*
   14260 ** Initialize the memory allocator.
   14261 **
   14262 ** This routine is not threadsafe.  The caller must be holding a mutex
   14263 ** to prevent multiple threads from entering at the same time.
   14264 */
   14265 static int memsys5Init(void *NotUsed){
   14266   int ii;            /* Loop counter */
   14267   int nByte;         /* Number of bytes of memory available to this allocator */
   14268   u8 *zByte;         /* Memory usable by this allocator */
   14269   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   14270   int iOffset;       /* An offset into mem5.aCtrl[] */
   14271 
   14272   UNUSED_PARAMETER(NotUsed);
   14273 
   14274   /* For the purposes of this routine, disable the mutex */
   14275   mem5.mutex = 0;
   14276 
   14277   /* The size of a Mem5Link object must be a power of two.  Verify that
   14278   ** this is case.
   14279   */
   14280   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   14281 
   14282   nByte = sqlite3GlobalConfig.nHeap;
   14283   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   14284   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   14285 
   14286   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   14287   mem5.szAtom = (1<<nMinLog);
   14288   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   14289     mem5.szAtom = mem5.szAtom << 1;
   14290   }
   14291 
   14292   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   14293   mem5.zPool = zByte;
   14294   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   14295 
   14296   for(ii=0; ii<=LOGMAX; ii++){
   14297     mem5.aiFreelist[ii] = -1;
   14298   }
   14299 
   14300   iOffset = 0;
   14301   for(ii=LOGMAX; ii>=0; ii--){
   14302     int nAlloc = (1<<ii);
   14303     if( (iOffset+nAlloc)<=mem5.nBlock ){
   14304       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   14305       memsys5Link(iOffset, ii);
   14306       iOffset += nAlloc;
   14307     }
   14308     assert((iOffset+nAlloc)>mem5.nBlock);
   14309   }
   14310 
   14311   /* If a mutex is required for normal operation, allocate one */
   14312   if( sqlite3GlobalConfig.bMemstat==0 ){
   14313     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   14314   }
   14315 
   14316   return SQLITE_OK;
   14317 }
   14318 
   14319 /*
   14320 ** Deinitialize this module.
   14321 */
   14322 static void memsys5Shutdown(void *NotUsed){
   14323   UNUSED_PARAMETER(NotUsed);
   14324   mem5.mutex = 0;
   14325   return;
   14326 }
   14327 
   14328 #ifdef SQLITE_TEST
   14329 /*
   14330 ** Open the file indicated and write a log of all unfreed memory
   14331 ** allocations into that log.
   14332 */
   14333 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   14334   FILE *out;
   14335   int i, j, n;
   14336   int nMinLog;
   14337 
   14338   if( zFilename==0 || zFilename[0]==0 ){
   14339     out = stdout;
   14340   }else{
   14341     out = fopen(zFilename, "w");
   14342     if( out==0 ){
   14343       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   14344                       zFilename);
   14345       return;
   14346     }
   14347   }
   14348   memsys5Enter();
   14349   nMinLog = memsys5Log(mem5.szAtom);
   14350   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   14351     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   14352     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   14353   }
   14354   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   14355   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   14356   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   14357   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   14358   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   14359   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   14360   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   14361   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   14362   memsys5Leave();
   14363   if( out==stdout ){
   14364     fflush(stdout);
   14365   }else{
   14366     fclose(out);
   14367   }
   14368 }
   14369 #endif
   14370 
   14371 /*
   14372 ** This routine is the only routine in this file with external
   14373 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   14374 ** struct populated with the memsys5 methods.
   14375 */
   14376 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   14377   static const sqlite3_mem_methods memsys5Methods = {
   14378      memsys5Malloc,
   14379      memsys5Free,
   14380      memsys5Realloc,
   14381      memsys5Size,
   14382      memsys5Roundup,
   14383      memsys5Init,
   14384      memsys5Shutdown,
   14385      0
   14386   };
   14387   return &memsys5Methods;
   14388 }
   14389 
   14390 #endif /* SQLITE_ENABLE_MEMSYS5 */
   14391 
   14392 /************** End of mem5.c ************************************************/
   14393 /************** Begin file mutex.c *******************************************/
   14394 /*
   14395 ** 2007 August 14
   14396 **
   14397 ** The author disclaims copyright to this source code.  In place of
   14398 ** a legal notice, here is a blessing:
   14399 **
   14400 **    May you do good and not evil.
   14401 **    May you find forgiveness for yourself and forgive others.
   14402 **    May you share freely, never taking more than you give.
   14403 **
   14404 *************************************************************************
   14405 ** This file contains the C functions that implement mutexes.
   14406 **
   14407 ** This file contains code that is common across all mutex implementations.
   14408 */
   14409 
   14410 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   14411 /*
   14412 ** For debugging purposes, record when the mutex subsystem is initialized
   14413 ** and uninitialized so that we can assert() if there is an attempt to
   14414 ** allocate a mutex while the system is uninitialized.
   14415 */
   14416 static SQLITE_WSD int mutexIsInit = 0;
   14417 #endif /* SQLITE_DEBUG */
   14418 
   14419 
   14420 #ifndef SQLITE_MUTEX_OMIT
   14421 /*
   14422 ** Initialize the mutex system.
   14423 */
   14424 SQLITE_PRIVATE int sqlite3MutexInit(void){
   14425   int rc = SQLITE_OK;
   14426   if( sqlite3GlobalConfig.bCoreMutex ){
   14427     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   14428       /* If the xMutexAlloc method has not been set, then the user did not
   14429       ** install a mutex implementation via sqlite3_config() prior to
   14430       ** sqlite3_initialize() being called. This block copies pointers to
   14431       ** the default implementation into the sqlite3GlobalConfig structure.
   14432       */
   14433       sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
   14434       sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   14435 
   14436       memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
   14437       memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
   14438              sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
   14439       pTo->xMutexAlloc = pFrom->xMutexAlloc;
   14440     }
   14441     rc = sqlite3GlobalConfig.mutex.xMutexInit();
   14442   }
   14443 
   14444 #ifdef SQLITE_DEBUG
   14445   GLOBAL(int, mutexIsInit) = 1;
   14446 #endif
   14447 
   14448   return rc;
   14449 }
   14450 
   14451 /*
   14452 ** Shutdown the mutex system. This call frees resources allocated by
   14453 ** sqlite3MutexInit().
   14454 */
   14455 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   14456   int rc = SQLITE_OK;
   14457   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   14458     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   14459   }
   14460 
   14461 #ifdef SQLITE_DEBUG
   14462   GLOBAL(int, mutexIsInit) = 0;
   14463 #endif
   14464 
   14465   return rc;
   14466 }
   14467 
   14468 /*
   14469 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   14470 */
   14471 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   14472 #ifndef SQLITE_OMIT_AUTOINIT
   14473   if( sqlite3_initialize() ) return 0;
   14474 #endif
   14475   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   14476 }
   14477 
   14478 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   14479   if( !sqlite3GlobalConfig.bCoreMutex ){
   14480     return 0;
   14481   }
   14482   assert( GLOBAL(int, mutexIsInit) );
   14483   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   14484 }
   14485 
   14486 /*
   14487 ** Free a dynamic mutex.
   14488 */
   14489 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   14490   if( p ){
   14491     sqlite3GlobalConfig.mutex.xMutexFree(p);
   14492   }
   14493 }
   14494 
   14495 /*
   14496 ** Obtain the mutex p. If some other thread already has the mutex, block
   14497 ** until it can be obtained.
   14498 */
   14499 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   14500   if( p ){
   14501     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   14502   }
   14503 }
   14504 
   14505 /*
   14506 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   14507 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   14508 */
   14509 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   14510   int rc = SQLITE_OK;
   14511   if( p ){
   14512     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   14513   }
   14514   return rc;
   14515 }
   14516 
   14517 /*
   14518 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   14519 ** entered by the same thread.  The behavior is undefined if the mutex
   14520 ** is not currently entered. If a NULL pointer is passed as an argument
   14521 ** this function is a no-op.
   14522 */
   14523 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   14524   if( p ){
   14525     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   14526   }
   14527 }
   14528 
   14529 #ifndef NDEBUG
   14530 /*
   14531 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   14532 ** intended for use inside assert() statements.
   14533 */
   14534 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   14535   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   14536 }
   14537 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   14538   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   14539 }
   14540 #endif
   14541 
   14542 #endif /* SQLITE_MUTEX_OMIT */
   14543 
   14544 /************** End of mutex.c ***********************************************/
   14545 /************** Begin file mutex_noop.c **************************************/
   14546 /*
   14547 ** 2008 October 07
   14548 **
   14549 ** The author disclaims copyright to this source code.  In place of
   14550 ** a legal notice, here is a blessing:
   14551 **
   14552 **    May you do good and not evil.
   14553 **    May you find forgiveness for yourself and forgive others.
   14554 **    May you share freely, never taking more than you give.
   14555 **
   14556 *************************************************************************
   14557 ** This file contains the C functions that implement mutexes.
   14558 **
   14559 ** This implementation in this file does not provide any mutual
   14560 ** exclusion and is thus suitable for use only in applications
   14561 ** that use SQLite in a single thread.  The routines defined
   14562 ** here are place-holders.  Applications can substitute working
   14563 ** mutex routines at start-time using the
   14564 **
   14565 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   14566 **
   14567 ** interface.
   14568 **
   14569 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   14570 ** that does error checking on mutexes to make sure they are being
   14571 ** called correctly.
   14572 */
   14573 
   14574 
   14575 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
   14576 /*
   14577 ** Stub routines for all mutex methods.
   14578 **
   14579 ** This routines provide no mutual exclusion or error checking.
   14580 */
   14581 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
   14582 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
   14583 static int noopMutexInit(void){ return SQLITE_OK; }
   14584 static int noopMutexEnd(void){ return SQLITE_OK; }
   14585 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
   14586 static void noopMutexFree(sqlite3_mutex *p){ return; }
   14587 static void noopMutexEnter(sqlite3_mutex *p){ return; }
   14588 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
   14589 static void noopMutexLeave(sqlite3_mutex *p){ return; }
   14590 
   14591 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   14592   static sqlite3_mutex_methods sMutex = {
   14593     noopMutexInit,